一直工作在这一整天似乎有一个编译错误。我需要它输出算术表达式:当{25 +(3-6)* 8}是输出时(它正确地做到这一点)有匹配的符号,但是当我输入一个不匹配的时候} {25 +(3-6)I在线程“主要” java.util.EmptyStackException错误得到一个异常Java匹配的圆括号
import java.util.*;
public class Comparison {
public static void main(String[] args) {
Stack<Character> stack = new Stack<>();
System.out.print("Please enter arithmetic expression: For example, the expression {25 + (3 – 6) * 8} ");
Scanner input = new Scanner(System.in);
String capture = input.nextLine();
// String[] pieces = capture.split("\\s+");
for (int i = 0; i < capture.length(); i++) {
char p = capture.charAt(i);
if (p == '{' || p == '(' || p == '[') {
stack.push(p);
}
char r = stack.peek();
if (p == '}' || p == ')' || p == ']')
{
if (p == '}' && r == '{' || p == ')' && r == '(' || p == ']' && r == '['){
stack.pop();
System.out.print("Arithmetic Expression: has matched symbols.");
}
else {
System.out.print("Arithmetic Expression: has mismatched symbols.");
}
}
}
}
}
该错误消息有很大的意义......它相当于一个'NullPointerExcepion',意思是堆栈中没有任何东西存在,但是您试图对其执行读取/弹出操作。你可以'try-catch'这个异常和'catch'你知道输入是坏的,因为它没有正确的括号。 – px06