package expressions; import java.util.Scanner; /* Recursively computes an arithmetic expression in infix notation */ public class Expression { static char lookahead; static Scanner sc = new Scanner(System.in); static String input = sc.nextLine(); static int ind = 0; public static void main(String[] args) { lookahead = getC(); try { double val = expr(); if (lookahead == '$') System.out.println(val); else System.out.println("Wrong Expression"); } catch (ExpressionError e) { System.out.println("Wrong Expression"); } } static double expr() throws ExpressionError { double val = term(); while (lookahead == '+' || lookahead == '-') if (lookahead=='+') { lookahead = getC(); val += term(); } else { lookahead = getC(); val -= term(); } return val; } static double term() throws ExpressionError { double val = factor(); while (lookahead == '*' || lookahead == '/') if (lookahead == '*') { lookahead = getC(); val *= factor(); } else { lookahead = getC(); val /= factor(); } return val; } static double factor() throws ExpressionError { double val; if (lookahead == '(') { lookahead = getC(); val = expr(); if (lookahead != ')') throw new ExpressionError(); lookahead = getC(); return val; } else if (Character.isDigit(lookahead)){ val = lookahead-'0'; while (Character.isDigit(lookahead = getC())) val = val*10+lookahead-'0'; return val; } else throw new ExpressionError(); } static char getC() { try { while(Character.isWhitespace(input.charAt(ind++))); return input.charAt(ind-1); } catch (Exception e) { return '$'; } } }