import java.util.ArrayList; import java.io.IOException; public class Infix { private ArrayList chars; private int index; public static void main(String[] args) { String str = "+++12-835"; if (args.length > 0) { str = args[0]; } try { Infix parser = new Infix(str); } catch (Exception e) { System.out.println("error"); } } public Infix(String terminals) throws IOException { this.index = 0; this.chars = new ArrayList(); for (char c: terminals.toCharArray()) this.chars.add(c); this.list(); if (this.index < this.chars.size()) throw new IOException("Could not parse entire string"); System.out.println(); } private void list() throws IOException { char lookahead = this.lookahead(); if (lookahead == '+' || lookahead == '-') { match(lookahead); System.out.write('('); list(); System.out.write(lookahead); list(); System.out.write(')'); } else if (lookahead >= '0' && lookahead <= '9') digit(); else throw new IOException("Expected lookahead to be a digit or plus/minus"); } private void digit() throws IOException { char lookahead = this.lookahead(); if (lookahead >= '0' && lookahead <= '9') { match(lookahead); System.out.write(lookahead); return; } throw new IOException("Expected lookahead to be a digit"); } private void match(char t) throws IOException { boolean matches = this.lookahead() == t; if (matches) this.index += 1; else if (!matches) throw new IOException("Expected " + (char)this.lookahead() + " to match " + (char)t); } private char lookahead() { return this.chars.get(this.index); } }