gpt4 book ai didi

java - Postfix 表示法中的 EmptyStackException

转载 作者:行者123 更新时间:2023-12-02 10:44:23 26 4
gpt4 key购买 nike

当我尝试运行后缀表达式时,由于我的字符串有两个背靠背的操作数,因此出现 EmptyStackException。我不知道如何在我的堆栈中捕获它。任何想法或想法都值得赞赏。

import java.util.Stack;
import java.util.Queue;

public class postFixCalc extends Program2Test{
static Program2Test<Integer> calcStack = new Program2Test<>();

private static int calc1(String exp) {
Stack<Integer> calc1Stack = new Stack<>();

for(int i = 0; i<exp.length(); i++) {
char c = exp.charAt(i);
if(Character.isDigit(c))
calc1Stack.push(c-'0');
else {
int val1= calc1Stack.pop();
int val2= calc1Stack.pop();

switch(c){
case '+':
calc1Stack.push(val2+val1);
break;

case '-':
calc1Stack.push(val2-val1);
break;

case '/':
calc1Stack.push(val2/val1);
break;

case '*':
calc1Stack.push(val2*val1);
break;
}
}
}
return calc1Stack.pop();
}
public static void main(String[] args) {

// TODO Auto-generated method stub
String exp = "12+4*5-";
System.out.println("Your Answer is: " + calc1(exp));
String exp2 = "(12*4*1-)/53+";
System.out.println("Your answer is: " + calc1(exp2));



}

}

最佳答案

将此添加到您的代码中以确保您不会从空堆栈中弹出:

if(!calc1Stack.empty()) {
int val1= calc1Stack.pop();
}

if(!calc1Stack.empty()) {
int val2= calc1Stack.pop();
}

然后处理else条件。

关于java - Postfix 表示法中的 EmptyStackException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52694892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com