gpt4 book ai didi

java - 为什么我会收到空​​堆栈异常?

转载 作者:行者123 更新时间:2023-12-01 13:12:37 34 4
gpt4 key购买 nike

请帮忙解决这个问题,错误显示为空堆栈异常。

代码:

import java.util.Stack;

public class Stacks {


public static void main(String[] arg)
{

String s[] = {"5 + ) * ( 2",
// " 2 + ( - 3 * 5 ) ",
"(( 2 + 3 ) * 5 ) * 8 ",
"5 * 10 + ( 15 - 20 ) ) - 25",
" 5 + ( 5 * 10 + ( 15 - 20 ) - 25 ) * 9"
};

for (int i = 0; i < s.length; i++)
{

Arithmetic a = new Arithmetic(s[i]);

if (a.isBalance())
{
System.out.println("Expression " + s[i] + " is balanced\n");
a.postfixExpression();
System.out.println("The post fixed expression is " + a.getPostfix());
a.evaluateRPN();

}
else
System.out.println("Expression is not balanced\n");
}
}

private static class Arithmetic {
String str = "";

Stack<Character> stack = new Stack<>();
String postFix = "";
public Arithmetic(String str)
{
this.str = str;
this.postFix = postFix;
}
private boolean isBalance()
{
Stack<Character> stack = new Stack<>();
for(int i = 0; i < str.length(); i++)
{

if(str.charAt(i) == '(' )
stack.push(str.charAt(i));
else if(str.charAt(i) == ')')
{
if(stack.isEmpty() || stack.pop() != '(')
return false;
}

}
return stack.isEmpty();


}

private void evaluateRPN() {

}

private String getPostfix() {
return postFix;
}

@SuppressWarnings("empty-statement")
private void postfixExpression() {
Stack<Character> stack = new Stack<>();
for(int i = 0; i < str.length(); i++)
{
if(Character.isDigit(str.charAt(i)))
postFix += " " + str.charAt(i);
else if(str.charAt(i) == '+' || str.charAt(i) == '-' ||
str.charAt(i) == '*' || str.charAt(i) == '/' ||
str.charAt(i) == '%' || str.charAt(i) == '(' ||
str.charAt(i) == ')' )
{
do{
stack.push(str.charAt(i));


}

while(stack.isEmpty());
}



if(str.charAt(i) == '(' || str.charAt(i) == ')')
{
if(str.charAt(i) == '(')
stack.push(str.charAt(i));
else if(str.charAt(i) == ')')
{
do
{
do{
postFix += stack.pop();
}while(stack.pop() != ')');
}while(!stack.empty());

}
}

if(str.charAt(i) == '+' || str.charAt(i) == '-' ||
str.charAt(i) == '*' || str.charAt(i) == '/' )
{
if(str.charAt(i) == '+' || str.charAt(i) == '-')
{
do{
postFix += stack.pop();
}while ((stack.pop() != '(') || !stack.empty());
postFix += str.charAt(i);
}
if(str.charAt(i) == '*' || str.charAt(i) == '/')
{
if(stack.pop() == '+' || stack.pop() == '-')
{
stack.push(str.charAt(i));
}
}
}
}
do{
postFix += stack.pop();
}while(!stack.empty());

}

}

}

最佳答案

当您测试时使用查看功能,否则您将删除该项目。当你这样做时:

if(stack.pop() == '+' || stack.pop() == '-')

并且您的堆栈包含[*]

当您调用 stack.pop() 时,您会删除 * ,之后您的堆栈将为空,并且您将在第二个测试中遇到异常 (stack. pop() == '-').

您需要验证您的代码并更改您的逻辑。

关于java - 为什么我会收到空​​堆栈异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736762/

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