import java.util.Scanner; /** * Provides a simple command-line calculator that supports single addition, subtraction, * multiplication, and divison. * *

Valid expressions are of the following form: NUM OP NUM, where NUM represents a decimal * number and OP is either a +, -, *, or /. Spaces are required to separate the numbers * from the operator. * *

This program demonstrates good use of if-else-if constructs, as well as defensive programming. * I think that this program will respond in a well-behaved manner (i.e. no crashes) to any * user input. If you find it to be otherwise, please let me know! * * @author pollen */ public class Calculator { public static void main(String[] args) { Scanner in = new Scanner(System.in); // Give the user a prompt. System.out.print("Enter expression: "); // Guard against bad numeric input. if (in.hasNextDouble()) { double firstNum = in.nextDouble(); // Read the operator in as a string, since we can't parse a plus or minus // sign as a double or an int. String operator = in.next(); // Guard against bad numeric input. if (in.hasNextDouble()) { double secondNum = in.nextDouble(); // Check the operator and perform the actual operation. if (operator.equals("+")) { System.out.println(firstNum + secondNum); } else if (operator.equals("-")) { System.out.println(firstNum - secondNum); // I know we didn't do multiplication and division in lecture, but I told you // they were pretty easy to add. Here they are: } else if (operator.equals("*")) { System.out.println(firstNum * secondNum); } else if (operator.equals("/")) { // And you probably thought you could crash the program by having it divide // by zero. Try it out (1/0) and you will learn something about how Java handles // doubles. You could also try 0/0 -- the result is different. System.out.println(firstNum / secondNum); } else { // The operator was not a plus or minus sign. Signal to the user that this is an error. System.out.println("Invalid operator: " + operator); } } else { // The second number was badly formed. System.out.println("Invalid number"); } } else { // The first number was badly formed. System.out.println("Invalid number"); } } }