calculator - break; case '*': System.out.println(left *...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
/* Sample Run: Welcome to our calculator. Enter a simple binary expression to evaluate, q to quit.: 23 * 132.32 Result is: Enter a simple binary expression to evaluate, q to quit: -.238/.00392 Result is: Enter a simple binary expression to evaluate, q to quit: q. Design: proposed methods Get expression() ==> String Get left operand (String expr) ==> double Get right operand (String expr) ==> double Get the operator (String expr) ==> int of where the operator is Addition (left, right) Subtraction (left, right) Multiplication (left, right) Division (left, right) */ import java.util.Scanner; public class calculator { static Scanner kb = new Scanner(System.in); public static void main(String[] args) { boolean quit = false; String expr; double left, right; int opIndex; char op; expr = getExpression(); while (! expr.equalsIgnoreCase("q")) { opIndex = getOp(expr); op =expr.charAt(opIndex); left = getLeft(expr, opIndex); right = getRight(expr, opIndex); op = getOp(expr); System.out.print("Result is: "); switch (op) { case '+': System.out.println(left + right);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: break; case '*': System.out.println(left * right); break; case '-': System.out.println(left - right); break; case '/': System.out.println(left / right); break; default: System.out.println("invalid operator."); } expr = getExpression(); } } public static String getExpression() { System.out.print("enter a simple binary arithmetic expression, q to quit: "); return kb.nextLine(); } public static double getLeft(String ex, int index) { return 0; } public static double getRight(String ex, int index) { return 0; } public static double getOp(String ex) { int index = -1 index = ex.indexOf('+'); if(ex.indexOf('+') > 0) return index; //return is like a break -- ends if, and entire statement. index = ex.indexOf('*'); return index; index = ex.indexOf('/'); return index; // deal with subtraction (could be negative numbers) index = ex.indexOf('_'); if (index < 1) // find next one index = ex.indexOf('-', 1); return 0; } }...
View Full Document

Page1 / 2

calculator - break; case '*': System.out.println(left *...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online