summaryrefslogtreecommitdiff
path: root/Homework/cs5300/homework-two/Infix.java
diff options
context:
space:
mode:
Diffstat (limited to 'Homework/cs5300/homework-two/Infix.java')
-rw-r--r--Homework/cs5300/homework-two/Infix.java72
1 files changed, 72 insertions, 0 deletions
diff --git a/Homework/cs5300/homework-two/Infix.java b/Homework/cs5300/homework-two/Infix.java
new file mode 100644
index 0000000..33c8dcf
--- /dev/null
+++ b/Homework/cs5300/homework-two/Infix.java
@@ -0,0 +1,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);
+ }
+}