In: Computer Science
5-Write an EBNF rules that describes the following while statement of Java. Then, write the recursive-descent subprogram in Java or C/C++ for the EBNF rule. Please summit your source code and a screen shot of the parsing of the following examples.
do { if ( number % 2 == 0 ) even ++; number=number+1; } while (number <= 10)
EBNF rules for while statement :
<while_stmt> -> WHILE ‘(‘ ( <arith_expr> | <logic_expr> ) ‘)’
<block> <block> -> <stmt> | ‘{‘ <stmt> {<stmt>} ‘}’
Source Code of the parsing of the given example :
import java.util.*;
public class ParseString
{
public static void main(String args[])
{
StringTokenizer st1 = new StringTokenizer("do { if ( number % 2 == 0 ) even ++ ; number = number + 1 ; } while ( number <= 10 ) ", " "); // StringTokenizer Class allows string to break into tokens.
int count=0;
while (st1.hasMoreTokens()) // It test if more tokens are available or not.
{
count++;
System.out.println("Token "+count+" "+st1.nextToken()); //Returns next token in the string.
}
System.out.println("Total Tokens :: "+count);
}
}
Output (Snapshot) :