我真的需要我的修复后表达式计算器的帮助。我真的不知道我编写的代码有什么问题,但是当我运行该程序时,它只是打印出顶部的数字。例如,如果我输入“7 2 +”,输出是2.如果我输入“2 7 +”,输出是7.有人请指出我如何解决这个问题的正确方向?我认为(不确定)问题是我的程序无法正确检测操作数“+”和“*”。但是,我不明白为什么。Java后缀表达式评估器
文件#1:
import java.io.*;
import java.util.*;
public class ProblemTwo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a post value expression: ");
String input = scan.nextLine();
StringTokenizer st = new StringTokenizer(input);
Stack hello = new Stack(st.countTokens());
for (int i = 0; i <= st.countTokens(); i++) {
String inputToken = st.nextToken();
if (inputToken.trim().contains("+")) {
int sum = Integer.parseInt(hello.pop() + Integer.parseInt(hello.pop()));
System.out.println(sum);
hello.push(Integer.toString(sum));
}
else if (inputToken.trim().contains("*")){
int product = Integer.parseInt(hello.pop()) * Integer.parseInt(hello.pop());
hello.push(Integer.toString(product));
}
else {
hello.push(inputToken);
}
}
System.out.println(hello.pop());
}
}
文件#2:
public class Stack {
private String[] stackArray;
private int arraySize;
private int top;
public Stack(int capacity) {
arraySize = capacity;
stackArray = new String[arraySize];
top = -1;
}
public void push(String i) {
stackArray[++top] = i;
}
public String pop() {
return stackArray[top--];
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == arraySize - 1;
}
}
你不应该用'返回stackArray [顶 - ]''中弹出()'? –
是否有理由维护一堆'String'而不是'int's? – Clashsoft
@Sudhir Singh对,我只是改变了它,但它仍然是一样的错误 – Hat