Java匹配括号

时间:2016-11-23 11:51:00

标签: java stack

整天都在努力,似乎有一个编译错误。我需要它来输出算术表达式:当输出{25 +(3 - 6)* 8}时它具有匹配的符号(它正确地执行此操作)但是当我输入不匹配的符号时} {25 +(3 - 6)I在线程" main"中获得异常java.util.EmptyStackException错误

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.");

              } 


      }


    }



}


   }

2 个答案:

答案 0 :(得分:0)

此时您需要检查堆栈当前是否为空:

 if (stack.size()==0){
    // message when the stack is empty: parenthesis not closed
     break;
 }
 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.");

          } 


  }


}

答案 1 :(得分:0)

我建议您在 POPING

时进行更改

as

  

if(p ==&#39;}&#39;&amp;&amp; r ==&#39; {&#39; || p ==&#39;)&#39; &安培;&安培; r ==&#39;(&#39; || p ==&#39;]&#39;&amp;&amp; r ==   &#39; [&#39;的&安培;&安培; stack.size()大于0

那就是它!