Code to check if a piece of code is legal.
Hey guys I'm having a bit of trouble with this and not sure if I'm doing it right. I know there is an easier way but I'm not sure how to do it. Also for the stack.peek() == '{' is that right because when I compile it, it comes up with incomparable types: java.lang.Object and char.
Any help would be appreciated.
Code:
import java.util.Stack;
/**
*
* @author ()
* @version ()
*/
public class Brackets
{
private String code;
/**
* Constructor for objects of class Brackets
*/
public Brackets(String text1)
{
code = text1;
}
/**
* checks if the code is legit or not.
*@return if it is legal or not.
*/
public boolean isLegal()
{
boolean legal = false;
Stack stack = new Stack();
for( int index = 0; index < code.length();index++)
{
char ch = code.charAt(index);
if(ch == '{')
{
stack.push(ch);
legal = true;
}
else if(ch == '(')
{
stack.push(ch);
}
else if(ch == '[' && legal == true)
{
stack.push(ch);
}
else if((ch == ']') && (stack.peek() == '[') && legal == true)
{
stack.pop();
}
else if((ch == ')') && (stack.peek() == '(') && legal == true)
{
stack.pop();
}
else if((ch == '}') && (stack.peek() == '{') && legal == true)
{
stack.pop();
}
else
{
legal = false;
}
}
return legal;
}
}