Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I've written out some of the code required already; I'm just not sure how to implement the algorithm outlined below. In Java: You will write

I've written out some of the code required already; I'm just not sure how to implement the algorithm outlined below.

In Java:

You will write a method that checks a given expression (a String) with characters and brackets ((), [], {}, <>), determine if it is well-formed by using the following algorithm in conjunction with a stack.

Check the expression character by character. If the character is an opening bracket (characters (, [, {, ), then:

Check if the stack is empty. If it is, then there is no matching opening bracket. The expression is not well formed.

If the stack is not empty, pop the top character off the stack, compare the current closing bracket to the top character. If they are matched brackets, continue to read next character in the expression; if they are not matched brackets, the expression is not well formed.

If the end of the expression is reached, check if the stack is empty. If it is, the expression is well-formed. Otherwise, it is not well-formed.

Your code should print meaningful error message when the expression is not well-formed. For example, missing open bracket if current character is a close bracket but stack is empty, missing close bracket if the end of string is reached but stack is not empty, or mismatch brackets.

Code:

import java.util.*;

public class BalanceCheck {

public static boolean balanceCheck(String s){ boolean result = true; Scanner sc = new Scanner(System.in); String brackets = sc.nextLine(); Stack stack = new Stack (); boolean missOpen = false; boolean missClose = false; boolean missMatch = false; char ch1 = ' '; char ch2 = ' '; for (int i=0; i

public static void main (String args[]){ String test = "[(test>)]"; boolean correct = balanceCheck(test); System.out.println("Is the stack empty?"); System.out.println(stack.isEmpty() + " , the string is not well formed."); if (correct) System.out.println("The string is well formed"); else System.out.println("The string is not well formed"); }

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Demystifying Databases A Hands On Guide For Database Management

Authors: Shiva Sukula

1st Edition

8170005345, 978-8170005346

More Books

Students also viewed these Databases questions

Question

Solve the following 1,4 3 2TT 5x- 1+ (15 x) dx 5X

Answered: 1 week ago