7 AnswersNew Answer
Let's go step by step: st1 = "(" atomicSentence() does nothing In complexSentence(), st1.equals("(") is true, so it gets the next token and calls sentence again In Sentence(), st1 = "P" atomicSentence() collects "P" st1 = "AND" In complexSentence(), st1.equals("(") is false. So else block is executed where connective() is called (line 88) connective() collects "AND" st1 = "Q" Now there are no more tokens. Any call to getTokens() will have no effect and `st1` will always be "Q". 1. On line 89, Sentence() is called again. 2. atomicSentence() does nothing. 3. In complexSentence(), st1.equals("(") is false. So else block is executed. 4. connective() does nothing. 5. Program is again on line 89, so step 1-5 are repeated again This is an infinite recursion which leads to a stack overflow. A very simple fix for this would be to only go furthur if there are more tokens (in the getTokens() method) using StringTokenizer.hasMoreTokens() and halting the parser otherwise
hi XXX, how will I tell the getTokens() to stop if there are no tokens left?
Azalea You can use hasMoreTokens() to check if there are tokens available. https://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html#hasMoreTokens()
Denise Roßberg hi, I tried putting an if condition (if tokens.hasMoreTokens()) on my getTokens() method, which you can see on my code now just edited it, but it did not work :< . can you help me identify where should i put it?
Azalea That's correct. Your problem is the return statement. It does not end the program but returns from getTokens() to the method which called getTokens()...call, return, call, return ... Instead of return you can use System.exit() to stop your program.
Denise Roßberg can I make it go back to the if(st1.equals(")") inside the complexSentence method?
You can call complexSequence() and see what happens. But I am wondering what you want to do when no tokens are left.