Skip to content

Instantly share code, notes, and snippets.

@JakWai01
Created May 20, 2021 11:08
Show Gist options
  • Save JakWai01/051d80c652681028613ed102c8d2071a to your computer and use it in GitHub Desktop.
Save JakWai01/051d80c652681028613ed102c8d2071a to your computer and use it in GitHub Desktop.
package appl_alg_interpreter;
import java.io.File;
public class ExpressionParser {
static ProgramScanner psc;
static String NAME = "[a-zA-Z_][a-zA-Z_0-9]*";
static String NUMBER = "(^|\\s+)((\\-?[0-9]+(\\.[0-9]*)?)|(-?\\.[0-9]+))($|\\s+)";
static String OPERATOR = "[\\+\\-\\*/]";
static class Node {
public String value;
public Node left;
public Node right;
public Node(String value, Node left, Node right) {
this.value = value;
this.left = left;
this.right = right;
}
public static Node expr(ProgramScanner psc) throws Exception {
String token = psc.nextTokenOrNull(NUMBER);
if (token != null) {
return new Node(token, null, null);
}
token = psc.nextTokenOrNull("\\(");
Node left = Node.expr(psc);
token = psc.nextToken(OPERATOR);
String value = token;
Node right = Node.expr(psc);
token = psc.nextTokenOrNull("\\)");
return new Node(value, left, right);
}
public Double evaluate() {
Double result = 0.0;
if (left == null)
return Double.parseDouble(value);
Double l = left.evaluate();
Double r = right.evaluate();
if (value.equals("+"))
result = l + r;
if (value.equals("-"))
result = l - r;
if (value.equals("*"))
result = l * r;
if (value.equals("/"))
result = l / r;
return result;
}
}
public static void main(String[] args) {
try {
psc = new ProgramScanner(new File("appls/appl_algs/Test.apl"));
Node result = Node.expr(psc);
System.out.println("Success");
System.out.println("Result = " + result.evaluate());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment