Hello,
I'm new to Java. I've written a simple program to match parentheses, curly braces and brackets. It works fine, but I can't figure out how to print out the position when a mismatch occurs.
For example: "(ab[c)" is should return that the mismatch is at position 3.
Any help would be appriciated.
Here is my code so far:
import java.util.*;
import java.util.Scanner;
import java.util.Stack;
public class Assignment3
{
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 = ']';
//declaring Parenthesis, Curly Braces and Brackets (left and right)
public static boolean isBalanced(String s) //if the input string is balanced (true/false)
{
Stack<Character> stack = new Stack<Character>(); //
for (int i = 0; i < s.length(); i++) //reading the string into the loop
{
if (s.charAt(i) == LEFTPARENT) stack.push(LEFTPARENT); //push the first left parenthesis onto the stack
else if (s.charAt(i) == LEFTBRACE) stack.push(LEFTBRACE); //push the first left Curly Brace onto the stack
else if (s.charAt(i) == LEFTBRACKET) stack.push(LEFTBRACKET); //push the first left Bracket onto the stack
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;
}
// all other characters will be ignored
}
return stack.isEmpty();
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a string with Parentheses, Brackets and curly braces: ");
String s = input.next();
{
if (isBalanced(s)== true)
System.out.println("The Parenthesis in"+" \""+ s +"\" "+"match");
if (isBalanced(s)== false)
System.out.println("The Parenthesis in"+" \""+ s +"\" "+ "do not match"+" ");
}
}
}