summaryrefslogtreecommitdiff
path: root/Homework/cs5300/homework-two/Infix.java
blob: 33c8dcfd73c7af37e0218bea3d5e6261df5c0d56 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.ArrayList;
import java.io.IOException;

public class Infix {
    private ArrayList<Character> 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<Character>();
        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);
    }
}