后缀计算器Java

Jma*_*z06 6 java stack calculator postfix-notation

好的,我必须从文件中读取后缀表达式.后缀表达式必须具有空格以分隔每个运算符或操作数.到目前为止,只有在输入文件中的运算符或操作数之间没有空格时,我才能使用它.(即如果文件有12+,我得到的结果是3.)为了做到这一点,我认为我需要对输入进行标记化,但我不确定如何.这就是我到目前为止所拥有的.感谢您的回复.

import java.util.*;
import java.io.*;
public class PostfixCalc{
public static void main (String [] args) throws Exception {
File file = new File("in.txt");
Scanner sc = new Scanner(file);
String input = sc.next();
Stack<Integer> calc = new Stack<Integer>();
while(sc.hasNext()){
for(int i = 0; i < input.length(); i++){
    char c = input.charAt(i);
    int x = 0;
    int y = 0;
    int r = 0;
    if(Character.isDigit(c)){
       int t = Character.getNumericValue(c);
        calc.push(t);
    }
    else if(c == '+'){
        x = calc.pop();
        y = calc.pop();
        r = x+y;
        calc.push(r);
    }
     else if(c == '-'){
        x = calc.pop();
        y = calc.pop();
        r = x-y;
        calc.push(r);
    }
     else if(c == '*'){
        x = calc.pop();
        y = calc.pop();
        r = x*y;
        calc.push(r);
    }
     else if(c == '/'){
        x = calc.pop();
        y = calc.pop();
        r = x/y;
        calc.push(r);
    }
}
 }
 int a = calc.pop();
System.out.println(a);
 }
 } 
Run Code Online (Sandbox Code Playgroud)

biz*_*lop 3

有几件事您需要更改,您可以逐步进行。

  1. 声明您Stack包含Integers 而不是Characters。
  2. 在读取输入的代码中,依赖Strings 而不是Characters。
  3. 使用 解析操作数Integer.parseInt()。这会将 s 转换StringIntegers。(实际上,它将它们转换为ints,但在您的情况下,这种差异并不重要。)
  4. Scanner.useDelimiter()使用to设置扫描仪分隔符\s+,这将匹配任何空白字符的序列。

当然还有无数其他方法来处理您的输入,但我试图让您了解如何更改现有代码以执行其需要执行的操作。