Untitled

Run Settings
LanguageJava
Language Version
Run Command
import java.util.*; import java.io.BufferedReader; import java.io.FileReader; public class interpreter { public static int evaluate(String expression, HashMap<String, Integer> hash) { String s = expression.substring(expression.indexOf("=")+1, expression.length()); char[] charray = s.toCharArray(); Stack<Integer> values = new Stack<Integer>(); Stack<Character> operations = new Stack<Character>(); for (int i = 0; i < charray.length; i++) { if( (charray[i] >= 'a' && charray[i] <= 'z') || (charray[i] >= 'A' && charray[i] <= 'Z')) { String p = String.valueOf(charray[i]); charray[i] = (char) hash.get(p).intValue(); } if (charray[i] == ' ') continue; if (charray[i] >= '0' && charray[i] <= '9') { StringBuffer sbuf = new StringBuffer(); while (i < charray.length && charray[i] >= '0' && charray[i] <= '9') sbuf.append(charray[i++]); values.push(Integer.parseInt(sbuf.toString())); } else if (charray[i] == '+' || charray[i] == '-' || charray[i] == '*' || charray[i] == '/') { while (!operations.empty() && hasPrecedence(charray[i], operations.peek())) values.push(applyOp(operations.pop(), values.pop(), values.pop())); operations.push(charray[i]); } } while (!operations.empty()) values.push(applyOp(operations.pop(), values.pop(), values.pop())); return values.pop(); } public static boolean hasPrecedence(char op1, char op2) { if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) return false; else return true; } public static int applyOp(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) throw new UnsupportedOperationException("Cannot divide by zero"); return a / b; } return 0; } public static void main( String [ ] args ) { Scanner scan = new Scanner(System.in); HashMap<String, Integer> h = new HashMap<String, Integer>(); try (BufferedReader br = new BufferedReader(new FileReader("espresso.txt"))) { String line; while ((line = br.readLine()) != null) { if (line.indexOf("read") != -1) { String s = line.substring(line.indexOf("read")+4, line.length()); System.out.println("Enter a value for the integer" + s); int x = scan.nextInt(); h.put(s, x); } if (line.indexOf("=") != -1) { String s = line.substring(0, line.indexOf("=")-1); String q = line.substring(line.indexOf("=")+2, line.length()); if (line.indexOf("+") != -1 || line.indexOf("-") != -1 || line.indexOf("*") != -1 || line.indexOf("/") != -1) { int var = evaluate(line, h); h.put(s, var); } else { int x = Integer.parseInt(q); h.put(s, x); } } if (line.indexOf("print") != -1) { String s = line.substring(line.indexOf("print")+6, line.length()); System.out.println(h.get(s)); } } } catch (NullPointerException e) { e.printStackTrace(); System.out.println("Undefined variable."); } catch (Exception t) { System.out.println("Syntax Error."); } scan.close(); System.out.println(h); }; }
read x y = 3 z = y * 3 print z
Editor Settings
Theme
Key bindings
Full width
Lines