Bracket Matching Assignment
Bracket Matching Assignment
import java.util.*;
public class BracketMatching {
static String input;
static String output = "";
public BracketMatching(String input){
this.input = input;
}
public static boolean checkBracketMatched(char leftBracket, char rightBracket){
boolean checkBracket = false;
if( (leftBracket == '(' && rightBracket == ')') || (leftBracket == '[' && rightBracket == ']') || (leftBracket ==
'{' && rightBracket == '}') ){
return true;
}
return checkBracket;
}
public static boolean checkLeftBracket(char current){
boolean check = false;
if( current == '{' || current == '[' || current == '(' ){
check = true;
}
return check;
}
public static boolean bracketMatched(){
int error = 0;
int currentPosition;
boolean check = false;
Stack <Character> stack = new Stack<Character>();
int last_position = input.length();
for(int position = 0; position < input.length(); position++){
char currentChar = input.charAt(position);
if( checkLeftBracket(currentChar) ){
stack.push(currentChar);
if( position == last_position-1 ){
output += "End of the string\n";
error += 1;
}
}
else{
if( stack.isEmpty() ){
output += "Error: no matching left for "+ currentChar + " at position "+(position+1) + ", the stack is
empty\n";
error += 1;
}
else{
char topStack = stack.peek();
if( checkBracketMatched(topStack,currentChar) ){
currentPosition = stack.size();
stack.pop();
output += "Bracket "+topStack+" at position "+(position) + " is matched with Bracket
"+currentChar+" at position "+(position+1)+"\n";
}
else{
output += "Error: no matching left bracket for "+currentChar + " at position "+(position+1)+"\n";
error += 1;
}
}
}
}
if(stack.isEmpty()){
check = true;
if(error == 0){
output += "Brackets successfully matched";
}
}else{
output += "Error: there are "+stack.size()+" left brackets in the stack without right brackets";
}
return check;
}
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println( " Enter any expression: ({[ ])} " );
String input = console.nextLine();
BracketMatching match = new BracketMatching(input);
if(bracketMatched()){
System.out.println(match.output);
}
else{
System.out.println(match.output +"\nBracket not matched");
}
}
}
OUTPUT: