我正在尝试评估一个后缀表达式,我可以为字符做,但这次尝试使用数字而不仅仅是单个数字。这是我的代码,
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]是一个数字,*不是数字,所以为什么它试图转换为数字;
由于