+ 1

Why do I keep on getting StackOverfloweError? in which part of my code is wrong? help pls

I am creating a recursive descent parse base on a bnf, but I keep on getting stack overflow error. here's my code so far.

26th Nov 2021, 6:20 AM
Azalea
7 odpowiedzi
+ 2
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
26th Nov 2021, 7:36 AM
XXX
XXX - avatar
0
hi XXX, how will I tell the getTokens() to stop if there are no tokens left?
26th Nov 2021, 7:38 AM
Azalea
0
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()
26th Nov 2021, 2:58 PM
Denise Ro├čberg
Denise Ro├čberg - avatar
0
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?
26th Nov 2021, 3:00 PM
Azalea
0
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.
26th Nov 2021, 3:31 PM
Denise Ro├čberg
Denise Ro├čberg - avatar
0
Denise Ro├čberg can I make it go back to the if(st1.equals(")") inside the complexSentence method?
26th Nov 2021, 11:38 PM
Azalea
0
You can call complexSequence() and see what happens. But I am wondering what you want to do when no tokens are left.
27th Nov 2021, 7:05 AM
Denise Ro├čberg
Denise Ro├čberg - avatar