This program actually reads in an input expression and using the grammar rule to determine whether the syntax is ok or not. This is a lexical analyzer. I need to be able to read in the input expression and output each token of the expression and it's token kind. I'm having some trouble with that code. Could someone help me?
import java.io.*;
public class grammar
{ private static StreamTokenizer tokens;
private static int token;
public static void main(String argv[]) throws IOException
{ InputStreamReader reader;
System.out.println("Enter Your Expression Ending with a SEMICOLON:");
if (argv.length > 0)
reader = new InputStreamReader(new FileInputStream(argv[0]));
else
reader = new InputStreamReader(System.in);
// create the tokenizer:
tokens = new StreamTokenizer(reader);
tokens.ordinaryChar('.');
tokens.ordinaryChar('-');
tokens.ordinaryChar('/');
// advance to the first token on the input:
getToken();
// check if expression:
expr();
// check if expression ends with ';'
if (token == (int)';')
System.out.println("Syntax ok");
else
System.out.println("Syntax error");
}
// getToken - advance to the next token on the input
private static void getToken() throws IOException
{ token = tokens.nextToken();
}
//expr - parse<expr> -> <term><term_tail>
private static void expr() throws IOException
{ term();
term_tail();
}
// term_tail - parse <term_tail> -> <add_op> <term> <term_tail> | Empty
private static void term_tail() throws IOException
{ if (token == (int)'+' || token == (int)'-')
{ add_op();
term();
term_tail();
}
}
// term - parse <term> -> <factor> <factor_tail>
private static void term() throws IOException
{factor();
factor_tail();
}
// factor_tail - parse <factor_tail> -> <mult_op> <factor> <factor_tail> | Empty
private static void factor_tail() throws IOException
{if (token == (int) '*' || token == (int) '/')
{mult_op();
factor();
factor_tail();
}
}
// factor - parse <factor> -> '(' <expr> ')' | '-' <expr> | number | identifier
private static void factor() throws IOException
{ if (token == (int)'(' )
{ getToken();
expr();
if (token == (int)')' )
getToken();
else System.out.println("closing ')' expected");
}
else if (token == (int)'-')
{ getToken();
factor();
}
else if (token == tokens.TT_NUMBER)
getToken();
else if (token == tokens.TT_WORD)
getToken();
else System.out.println("factor expected");
}
// add_op - parse <add_op> -> '+' | '-'
private static void add_op() throws IOException
{ if (token == (int)'+' || token == (int)'-')
getToken();
}
// mult_op - parse <mult_op> -> '*' | '/'
private static void mult_op() throws IOException
{ if (token == (int)'*' || token == (int)'/')
getToken();
}
}