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;
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…