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:
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!