【发布时间】:2018-01-21 19:20:05
【问题描述】:
在这个程序中,我试图检查输入字符串中的括号是否平衡。例如,(9*[3+4]) 是正确的,{10/[4+9) 不是。但是,每当我尝试运行我的程序并输入输入时。
出现了很多问题。当我输入字符串([{}]) 时,它说括号不平衡,当我输入([]) 时,它给了我一个空堆栈异常。我对堆栈的想法还很陌生,所以我遇到了很多麻烦。
import java.io.*;
import java.util.*;
import java.util.Stack;
public class BracketCheck {
public static void main(String args[]) {
Stack stk = new Stack();
Scanner s = new Scanner(System.in);
boolean balance = true;
System.out.println("Enter a string");
String str = s.nextLine();
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) == '(' || str.charAt(i) == '['
|| str.charAt(i) == '{') { //if the char is an opening bracket then add to stack
stk.push(str.charAt(i));
}
else if(str.charAt(i) == ')' || str.charAt(i) == ']' ||
str.charAt(i) == '}') { //if char is a closing bracket
if(!stk.isEmpty()) {
System.out.println(stk.peek()); // to check if the bracket was added
if((stk.pop().equals('(') && str.charAt(i) != ')') ||
(stk.pop().equals('[') && str.charAt(i) != ']') ||
(stk.pop().equals('{') && str.charAt(i) != '}')) {
// this is where i believe the empty stack exception occurs
balance = false;
System.out.println("Brackets don't match");
break;
}
}
else { // flase because there is no opeing bracket to match with the closing bracket
balance = false;
System.out.println("There is no opening bracket");
break;
}
}
}
if (balance == true) {
System.out.println("The equation is balanced");
}
else {
System.out.println("The equation is not balanced");
}
}
}
【问题讨论】:
-
旁白:
if ("([{".indexOf(str.charAt(i)) >= 0)是一种更简单的方法来检查您是否在左括号中。