From 6bf4b90c90f15f4ab60833bddf5b5756d1a6b1f6 Mon Sep 17 00:00:00 2001 From: Elizabeth Alexander Hunt Date: Thu, 2 Jul 2026 11:55:17 -0700 Subject: Init --- Homework/cs5300/homework-two/Infix.java | 72 +++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Homework/cs5300/homework-two/Infix.java (limited to 'Homework/cs5300/homework-two/Infix.java') 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 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); + } +} -- cgit v1.3