Results 1 to 4 of 4
- 08-29-2010, 09:24 AM #1
Member
- Join Date
- Aug 2010
- Posts
- 10
- Rep Power
- 0
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.
Java 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; } }Last edited by Eranga; 08-30-2010 at 04:21 AM. Reason: code tags added
- 08-29-2010, 09:49 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,413
- Blog Entries
- 7
- Rep Power
- 17
You are using a 'raw' Stack, i.e. it can only store and retrieve Objects; generics can solve this little issue: use a Stack<Character> instead and autoboxing does the implicit casting for you.
kind regards,
Jos
- 08-29-2010, 08:53 PM #3
Member
- Join Date
- Aug 2010
- Posts
- 10
- Rep Power
- 0
Thanks very much got it working now. i knew it was something simple.
Cheers for that
Vahshir.
- 08-30-2010, 04:21 AM #4
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
Please use code tags next time.
Similar Threads
-
can somebody check my code
By raven in forum New To JavaReplies: 2Last Post: 08-29-2010, 08:55 PM -
can anyone check my code?
By Harmesh Goyal in forum New To JavaReplies: 8Last Post: 06-29-2010, 05:43 AM -
small piece of code: cannot set a max
By senca in forum New To JavaReplies: 1Last Post: 03-06-2010, 08:26 PM -
Decode this piece of Code
By mikeyl62 in forum New To JavaReplies: 2Last Post: 02-27-2010, 08:59 PM -
Plz Some one check my code
By TamTam in forum AWT / SwingReplies: 1Last Post: 02-07-2009, 11:24 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks