# Stack Practice: Evaluating Expressions Syntax

• October 4th, 2011, 10:25 PM
Staticity
Stack Practice: Evaluating Expressions Syntax
Alright, so I'm a CS1 student.. who self taught himself all of the CS1 curriculum... and is now working on CS2 work. So I'm kind of out of my league on this one, without much guidance.. (That's why I love this site!) So... CS2 is currently practicing basic uses of Stacks with Expressions... Here is an example of Input/Output:

Input:
(hey)
Output:
true

Input:
([a+1])
Output:
false

Input:
( { ] )
Output:
false

So, it's basically just checking if the correct "close" symbol matches up with the previous "open" symbol.. Here is my Code:

Code :

``` public boolean checkSyntax2(String s){   Stack<Character> stack = new Stack<Character>();   char[] open = {'(', '[', '{', '<'}; char[] close = {')', ']', '}', '>'}; char c = '-';   for(int a = 0; a < s.length(); a++){ for(int i = 0; i < open.length;i++){ if(s.charAt(a) == open[i]){ c = open[i]; stack.push(s.charAt(a)); } else if(s.charAt(a) == close[i]){ if(!stack.isEmpty() && c == stack.peek()) stack.pop(); } } } if(stack.isEmpty()) return true; return false; }```

My Code works in all cases except for one like so: "([])"... As you can see within the first IF statement within the Nested For Loop, I have a line that says to set the char c equal to open[i]... c = open[i].. Well, this doesn't retain c, so if I have "([])", it pushes the "(" on the stack, makes c="(", then pushes "[" on to the stack and makes c="["... So the char c was overwritten. How can I retain each open character I have? I know I could use an ArrayList, but I don\'t exactly see how it can work that way.. Also I think a second Stack could be helpful, but I believe my CS teacher told me you would only need one Stack per method.. Sorry, I know it\'s a lot of information, but any help would be Greatly Appreciated!
• October 4th, 2011, 10:31 PM
helloworld922
Re: Stack Practice: Evaluating Expressions Syntax
c isn\'t necessary at all, or another way to think about it is c is always whatever is on top of the stack.

Algorithm:

1. For each character in the string
a. If it\'s an open character, push it onto the stack
b. If it\'s a close character, try to pop the top item off the stack. If you can\'t or it doesn\'t match the close character, there\'s a problem.
2. If after iterating through every character there are still items left on the stack, there\'s a problem.
• October 4th, 2011, 10:35 PM
Staticity
Re: Stack Practice: Evaluating Expressions Syntax
Quote:

Originally Posted by helloworld922
c isn't necessary at all, or another way to think about it is c is always whatever is on top of the stack.

Oh haha! take out C, and in the else if statement, just check if open[i] = stack.peek() !

Thanks a lot HelloWorld! I have no idea why my teacher suggested a character to be placed in there :/