gpt4 book ai didi

java - 是什么导致我收到此 EmptyStackException?

转载 作者:太空宇宙 更新时间:2023-11-04 13:08:30 26 4
gpt4 key购买 nike

我的程序采用后缀表达式并将其更改为中缀表达式。

我在代码中包含了两个错误原因,即程序没有足够的运算符以及输入不是有效的数字或运算符。

当我输入不好的输入时,错误会被捕获,但是,当在扫描仪中输入正确的输入时,它会出现以下错误:

Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at PostfixToInfix.change(PostfixToInfix.java:67)
at PostfixToInfix.main(PostfixToInfix.java:27)

我的代码需要更改什么?代码:

import java.util.Scanner;
import java.util.Stack;
import java.util.EmptyStackException;

public class PostfixToInfix
{
int x = 0;

public static void main(String[] args)
{
PostfixToInfix exp = new PostfixToInfix();
Scanner stdin =new Scanner(System.in);


try {
boolean inputNeeded = true;
int value = 0;

while(inputNeeded){
System.out.print("Postfix : ");
if(stdin.hasNextInt()){
inputNeeded = false;
}
else{
throw new Error("Not a number or valid operator");
}
}
String pf = stdin.nextLine().replaceAll("\\s+", "");
System.out.println("Infix : "+exp.change(pf));

}
catch (EmptyStackException e) {
System.out.println("Too few operators to produce a single result.");
}


}

static boolean isOperator(char c)
{
if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^')
{
return true;
}
return false;

}
boolean empty() //whether the stack is empty
{
return x == 0;

} // end empty

public String change(String pf)
{
Stack<String> s = new Stack<>();

for(int i = 0; i < pf.length(); i++)
{
char z = pf.charAt(i);
if(isOperator(z))
{
String x = s.pop();
String y = s.pop();
s.push("("+y+z+x+")");
}
else
{
s.push(""+z);
}

}
return s.pop();
}
}

最佳答案

考虑输入1 1 +

  • 扫描器读取1并将其存储在value中。
  • 扫描程序读取剩余的字符串,并将其修改后的版本 ("1+") 存储在 pf 中,并作为参数传递给 change 方法。
  • charAt 返回 pf 的第一个字符('1'),isOperator 返回 false,然后执行 else block ,将 "1" 压入堆栈。
  • charAt 返回 pf 的第二个字符('+'),isOperator 返回 true,然后执行 if block 。
  • pop 被调用一次,删除堆栈中唯一的元素 "1",并将其分配给 x。堆栈现在为空,第二次调用 pop 会导致 EmptyStackException

如果您的 IDE 还没有调试器,这是调试代码的方法。通过这一点,您应该发现使用 nextInt 是问题所在,因为当 if block 期望有两个数字时,剩余字符串中只会出现一个数字。

关于java - 是什么导致我收到此 EmptyStackException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34191972/

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