2016-11-23 146 views
-2

一直工作在這一整天似乎有一個編譯錯誤。我需要它輸出算術表達式:當{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."); 

       } 


     } 


    } 



} 


    } 
+0

該錯誤消息有很大的意義......它相當於一個'NullPointerExcepion',意思是堆棧中沒有任何東西存在,但是您試圖對其執行讀取/彈出操作。你可以'try-catch'這個異常和'catch'你知道輸入是壞的,因爲它沒有正確的括號。 – px06

回答

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

      } 


    } 


} 
+0

工作就像一個魅力。謝謝 – JavaCompilexx

0

我會建議只是一個雖然POPING變化

as

如果(P == '}' & &ř== '{' || p == ')' & &ř== '(' || p == ']' & &ř== '[' & & stack.size()> 0

這它!