import java.io.*; import java.util.*; /** * Naive integer expression calculator application, * Repeatedly reads an expression of form double {op double} from * standard input and prints ts value to standard output (op is +|-|*|/). * It reports an error if the expression is not well formed. * R.W. Topor, February 1999, updated March 2007! */ public class Calc { /** Main program. */ public static void main(String[] args) throws IOException { // Setup frame Calc app = new Calc(); app.run(); } /** Repeatedly reads and evaluates expressions and prints results. */ private void run() throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Read the first expression String expr = in.readLine(); while (expr != null) { try { // Evaluate the expression double val = evaluate(expr); // Print the value System.out.println(val); } catch (Exception e) { System.out.println("Syntax error"); } // Read the next expression expr = in.readLine(); } } /** Returns the double value of the (well-formed) expression. */ private double evaluate (String expr) throws Exception { StringTokenizer st = new StringTokenizer(expr, "+-*/", true); double val = Double.valueOf(st.nextToken().trim()).doubleValue(); while (st.hasMoreTokens()) { char op = st.nextToken().charAt(0); double num = Double.valueOf(st.nextToken().trim()).doubleValue(); switch (op) { case '+' : val += num; break; case '-' : val -= num; break; case '*' : val *= num; break; case '/' : val /= num; break; default : throw new Exception(); } } return val; } }