JavaCompilexx JavaCompilexx - 10 days ago 4
Java Question

Java Matching parenthesis

Been working on this all day there seems to be a compilation error. I need it to output Arithmetic Expression: has matched symbols when {25 + (3 – 6) * 8} is the output(it does this correctly) but when I input a mismatching one like }{25 + (3 – 6) I get an Exception in thread "main" java.util.EmptyStackException error

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

}


}


}



}


}

Answer

You need to check if stack is currently empty at this point:

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

          } 


  }


}
Comments