检查([和{表达式?)的正确数量?

时间:2016-03-02 07:16:42

标签: java stack

我正在尝试为我的java类编写一个程序。该程序应该使用Tokenization和Stack类来检查表达式中括号,括号和括号的正确平衡。

我做错了什么?

我的代码

   import java.util.*;
   public class Lab10 {
   public static void main(String[] args) throws Exception {
        Stack<String> stack = new Stack<>();        
        Scanner input = new Scanner(System.in);
        System.out.print("Enter string: ");
        String s = input.nextLine();
        input.close();      
        StringTokenizer tokens = new StringTokenizer(s, "[] () {}", true);
        while (tokens.hasMoreTokens()) {
            String token = tokens.nextToken().trim();
            if (token.compareTo("(") == 0 || token.compareTo("{") == 0 ||
                 token.compareTo("[") == 0) {
                stack.push(token);
            }

            else if (token.compareTo(")") == 0 || token.compareTo("}") == 0        ||
                token.compareTo("]") == 0) {
            String popped = stack.pop();

            if (token.compareTo(")") == 0 && popped.compareTo("(") != 0 ||
                token.compareTo("}") == 0 && popped.compareTo("{") != 0 ||
                token.compareTo("]") == 0 && popped.compareTo("[") != 0) {
                System.out.println("Error");
            }
        }

    }

    }
    }

1 个答案:

答案 0 :(得分:0)

正如@Eran所建议的那样,这些可能是代码的一些很好的改变:

if(stack.empty()) {
    System.out.println("Error");
    break;
}
String popped = stack.pop();
if (token.compareTo(")") == 0 && popped.compareTo("(") != 0 || token.compareTo("}") == 0 && popped.compareTo("{") != 0 || token.compareTo("]") == 0 && popped.compareTo("[") != 0) {
    System.out.println("Error");
    break;
}