import java.util.Scanner; /** Let's use a stack to see if an expression has matching parentheses. */ public class Paren { public static void main(String [] args) { System.out.printf("Enter an expression: "); Scanner kbd = new Scanner(System.in); String line = kbd.nextLine(); LinkedListStack stack = new LinkedListStack(); // Each time we see a '(', push it on the stack. // Each time we see a ')', pop its corresponding '(' from the stack. // For other characters, we just ignore. // Reject input when 1 of 2 cases occurs: // The stack is not empty when finished with input. // Try to pop from empty stack (right with no left). boolean goodInput = true; for (int i = 0; i < line.length(); ++i) { char c = line.charAt(i); if (c == '(') stack.push(new Character (c)); else if (c == ')') { // When we see the ')', the stack must not be empty. if (stack.size() == 0) { goodInput = false; break; } stack.pop(); } else continue; } // Stack should be empty when we're done reading input. if (stack.size() > 0) goodInput = false; // output System.out.printf("Your input is %s\n", goodInput ? "good" : "bad"); } }