Question: Chapter 20: Lists, Stacks, Queues, and Priority Queues programming Exercises : 20.11 - (Match grouping symbols) a Java program continues various pairs of grouping symbols,

Chapter 20: Lists, Stacks, Queues, and Priority Queues

programming Exercises: 20.11 - (Match grouping symbols) a Java program continues various pairs of grouping symbols, such as

Parentheses: (and)

Braces: {and}

Brackets: [and]

Note that the grouping symbols cannot overlaps. For example. (a{b)} is illegal. Write a program to check whether a Java source-code file has correct pairs of grouping symbols.

package sample; import java.util.Scanner; import java.util.Stack;

public class Controller { private static final char LEFTPARENT = '('; private static final char RIGHTPARENT = ')'; private static final char LEFTBRACE = '{'; private static final char RIGHTBRACE = '}'; private static final char LEFTBRACKET = '['; private static final char RIGHTBRACKET = ']';

public static boolean isBalanced(String s) { Stack stack = new Stack(); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == LEFTPARENT) stack.push(LEFTPARENT); else if (s.charAt(i) == LEFTBRACE) stack.push(LEFTBRACE); else if (s.charAt(i) == LEFTBRACKET) stack.push(LEFTBRACKET); else if (s.charAt(i) == RIGHTPARENT) { if (stack.isEmpty()) return false; if (stack.pop() != LEFTPARENT) return false; } else if (s.charAt(i) == RIGHTBRACE) { if (stack.isEmpty()) return false; if (stack.pop() != LEFTBRACE) return false; } else if (s.charAt(i) == RIGHTBRACKET) { if (stack.isEmpty()) return false; if (stack.pop() != LEFTBRACKET) return false; } } return stack.isEmpty(); }

public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.println("Enter a string with parentheses, brackets or curly braces: "); String s = input.next(); if (isBalanced(s)) System.out.println("The symbols in \""+ s +"\" match"); else System.out.println("The symbols in \""+ s + "\" do not match"); System.out.println(); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!