我正在尝试评估后缀表达式,我可以对字符进行评估,但这次尝试对数字进行评估,而不仅仅是单个数字。这是我的代码,
package test;
import java.util.Stack;
public class EvaluatePostfix {
public static int solution(String postfix){
Stack<Integer> stack = new Stack<Integer>();
int sum = 0;
int val1 = 0;
int val2 = 0;
String[] str = postfix.split(" ");
for(int i =0; i<str.length; i++){
if(Character.isDigit(postfix.charAt(i))){
stack.push(Integer.parseInt(str[i]));
System.out.println(stack.peek());
}
else{
//System.out.println(stack.peek());
val1 = stack.pop();
val2 = stack.pop();
switch(str[i].charAt(0)){
case '+':
stack.push(val1 + val2);
sum += val2;
break;
case '-':
stack.push(val1 - val2) ;
sum -= val2;
break;
case '/':
stack.push(val1 / val2) ;
sum /= val2;
break;
case '*':
stack.push(val1 * val2) ;
sum *= val2;
break;
}
//System.out.println(sum);
}
//System.out.println(stack.pop());
}
return stack.pop();
}
public static void main(String[]args){
String test = "10 20 30 * +";
//solution(test);
System.out.println(solution(test));
}
}
我有 10, 20 作为输出,它不输出 30 * +
我还有一个错误,内容如下,
Exception in thread "main" java.lang.NumberFormatException: For input string: "*"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:449)
at java.lang.Integer.parseInt(Integer.java:499)
at test.EvaluatePostfix.solution(EvaluatePostfix.java:18)
at test.EvaluatePostfix.main(EvaluatePostfix.java:60)
我不知道为什么会出现这个错误,我清楚地检查了 str[i] 是一个数字,* 不是一个数字,那么为什么它会尝试转换为数字;
谢谢
最佳答案
您正在检查错误的数字字符:此表达式 postfix.charAt(i)
未检查正确的字符,因为索引 i
超出了与原始字符串 postfix
中的位置同步。您的循环使用 i
来索引 str
数组,因此索引从零到标记数,而不是从零到字符串长度。
改用这个表达式:
if(Character.isDigit(str[i].charAt(0))) {
...
} ...
关于java - 评估后缀表达式,例如,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24845012/