I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expression. It needs to handle ( { [ ] } ) each open needs to balance with its corresponding closing bracket. For example a user could input [({})] which would be balanced and }{ would be unbalanced. This doesn't need to handle letters or numbers. I need to use a stack to do this.
I was given this pseudocode but can not figure how to implement it in java. Any advice would be awesome.
Update- sorry forgot to post what i had so far. Its all messed up because at first i was trying to use char and then i tried an array.. im not exactly sure where to go.
import java.util.*;
public class Expression
{
Scanner in = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
public boolean check()
{
System.out.println("Please enter your expression.");
String newExp = in.next();
String[] exp = new String[newExp];
for (int i = 0; i < size; i++)
{
char ch = exp.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(i);
else if (ch == ')'|| ch == ']' || ch == '}')
{
//nothing to match with
if(stack.isEmpty())
{
return false;
}
else if(stack.pop() != ch)
{
return false;
}
}
}
if (stack.isEmpty())
{
return true;
}
else
{
return false;
}
}
}
I hope this code can help:
import java.util.Stack;
public class BalancedParenthensies {
public static void main(String args[]) {
System.out.println(balancedParenthensies("{(a,b)}"));
System.out.println(balancedParenthensies("{(a},b)"));
System.out.println(balancedParenthensies("{)(a,b}"));
}
public static boolean balancedParenthensies(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}