Skip to content

Instantly share code, notes, and snippets.

@sanrodari
Created January 15, 2013 15:39
Show Gist options
  • Select an option

  • Save sanrodari/4539529 to your computer and use it in GitHub Desktop.

Select an option

Save sanrodari/4539529 to your computer and use it in GitHub Desktop.
Infix to postfix translator
package com.example;
import java.io.*;
class Parser {
static int lookahead;
public Parser() throws IOException {
lookahead = System.in.read();
}
void expr() throws IOException {
term() ;
while(true) {
if( lookahead == '+' ) {
match('+') ; term() ; System.out.write('+') ;
}
else if( lookahead == '-' ) {
match('-'); term(); System.out.write('-');
}
else return;
}
}
void term() throws IOException {
if (Character.isDigit((char) lookahead)) {
System.out.write((char) lookahead);
match(lookahead);
}
else throw new Error("syntax error");
}
void match(int t) throws IOException {
if( lookahead == t ) lookahead = System.in.read() ;
else throw new Error("syntax error");
}
}
public class Postfix {
public static void main(String[] args) throws IOException {
Parser parse = new Parser();
parse.expr();
System.out.write('\n');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment