I copied this program from a textbook (Compilers Principles, Techniques and Tools) and changed somethings in it to do what I wanted. It's a program to translate infix expressions into pretfix form. Here's the code:
package prefixTrans;
import java.io.*;
public class Parser {
static int lookahead;
public Parser() throws IOException{
lookahead = System.in.read();
}
void exp() throws IOException{
while(true) {
if (lookahead == '*'){
match('*'); System.out.write('*'); exp(); term();
}
else if (lookahead == '/'){
match('/'); System.out.write('/'); exp(); term();
}
else return;
}
}
void term() throws IOException{
if (lookahead == '+'){
match('+'); System.out.write('+'); factor(); term();}
else if (lookahead == '-'){
match('-'); System.out.write('-'); factor(); term();}
else return;
}
void factor() throws IOException{
if ( Character.isDigit((char)lookahead)) {
int v = 0;
while(Character.isDigit((char)lookahead)){
v = v * 10 + lookahead;
}
}
else if(Character.isAlphabetic(lookahead)){
String lexeme = "";
while(Character.isLetter(lookahead)){
lexeme = lexeme + lookahead;
}
}
System.out.write((char)lookahead); match(lookahead);
}
void match(int t) throws IOException{
if(lookahead == t) lookahead = System.in.read();
else throw new Error("syntax error");
}
public static void main(String [] args) throws IOException{
Parser parse = new Parser();
parse.exp(); System.out.write('\n');
}
}
Every time I enter an an input in the console inside Eclipse the program terminates.
I've edited my code, it doesn't terminate now but I get no output. here's the edited one:
package prefixTrans;
import java.io.*;
import java.util.Scanner;
public class Parser {
static int lookahead;
Scanner input;
public Parser() throws IOException{
//lookahead = System.in.read();
input = new Scanner(System.in);
lookahead = input.next().charAt(0);
}
void exp() throws IOException{
if (lookahead == '*'){
match('*'); System.out.write('*');exp();term();
}
else if (lookahead == '/'){
match('/'); System.out.write('/');exp();term();
}
else term();
}
void term() throws IOException{
if (lookahead == '+'){
match('+'); System.out.write('+'); factor(); term(); }
else if (lookahead == '-'){
match('-'); System.out.write('-'); factor(); term(); }
else factor();
}
void factor() throws IOException{
if ( Character.isDigit((char)lookahead)) {
int v = 0;
while(Character.isDigit((char)lookahead)){
v = v * 10 + lookahead;
}
}
else if(Character.isLetter(lookahead)){
String lexeme = "";
while(Character.isLetter(lookahead)){
lexeme = lexeme + lookahead;
}
}
System.out.write((char)lookahead); match(lookahead);
}
void match(int t) throws IOException{
if(lookahead == t) /*lookahead = System.in.read();*/ lookahead = input.next().charAt(0);
else throw new Error("syntax error");
}
public static void main(String [] args) throws IOException{
Parser parse = new Parser();
parse.exp(); System.out.write('\n');
}
}