0

Official problem:

Write Java method to perform recursive descent parse of the following production:

<repeat_statement> -> REPEAT <statement> UNTIL <expression> ;

This is what I've come up with:

void repeatStatement() {
 if(token == REPEAT) {
 token = getNextToken();
 if(parseStatement()) {
 if(token == UNTIL) {
 token = getNextToken();
 if(parseExpression()) {
 if(token == ;) {
 return true
 }
 }
 }
 } return false
 }

I'm pretty confident that I have the general idea here, but I was hoping that someone could help me polish this/ confirm that I'm on the right track.

BenMorel
37k52 gold badges208 silver badges339 bronze badges
asked Jan 29, 2012 at 20:45
0

1 Answer 1

2

It looks (vaguely) like you're trying to evaluate the repeat statement. That's not what recursive descent parsing does. I'd expect something like this (in pseudocode):

RepeatStatement repeat_statement() throws ParseException {
 if (!consume("REPEAT")) {
 throw new ParseException("no REPEAT token");
 }
 Statement statement = statement();
 if (!consume("UNTIL")) {
 throw new ParseException("no UNTILtoken");
 }
 Expression expression = expression();
 if (!consume(";")) {
 throw new ParseException("no closing semicolon");
 }
 return new RepeatStatement(statement, expression);
}
answered Jan 29, 2012 at 20:52
Sign up to request clarification or add additional context in comments.

2 Comments

Would you mind taking a look at the new code I posted? I tried to do some more research and think I may have come up with something half-way decent...
@tommy1370 - I assume that token is some sort of global variable. You need to decide whether, on entry to a parse method, token is the first token of the expression expected or whether it is the last token (if any) of what came before. Your method as it stands assumes the former on entry and before calls to parseStatement() and parseExpression(), but leaves token at the semicolon at the end. Presumably the calling method would compensate for that. Also, your method is declared void but you're trying to return a boolean value.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.