Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Complete the body of this method. You do not need to check the precondition. You

ID: 3645158 • Letter: C

Question

Complete the body of this method. You do not need to check the precondition. You may use the CharStack class.


public static boolean balanced(String p)
// Precondition: Each character of p is '(', ')', '{' or '}'.
// Postcondition: The method returns true if the characters form a
// sequence of correctly balanced parentheses with each '(' matching
// a ')' and each '{' matching a '}'. Note that a sequence such as
// ( { ) } is NOT balanced because when we draw lines to match the
// parentheses to their partners, the lines cross each other. On the
// other hand, ( { } ) and { ( ) } are both balanced.

Explanation / Answer

declare a character stack while ( more input is available) { read a character if ( the character is a '(' or '{' ) push it on the stack else if ( the character is a ')' or '}' and the stack is not empty ) pop a character off the stack else print "unbalanced" and exit } print "balanced"

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote