163k views
4 votes
Write a simple calculator program. Your program should ask for three things two whole numbers and an operator in the form of an expression like: 3 * 2 Use a select case structure to determine what operation needs to be performed on the two numbers. Your program should handle the arithmetic functions Add, Subtract, Multiply, and Divide (Depending on the operator entered).

User Malvin
by
5.1k points

1 Answer

6 votes

Answer:

The solution code is written in Java.

  1. Scanner input = new Scanner(System.in);
  2. System.out.print("Enter operator: ");
  3. String operator = input.nextLine();
  4. System.out.print("Enter first integer: ");
  5. int num1 = input.nextInt();
  6. System.out.print("Enter second integer: ");
  7. int num2 = input.nextInt();
  8. int result = 0;
  9. switch(operator){
  10. case "+":
  11. result = num1 + num2;
  12. break;
  13. case "-":
  14. result = num1 - num2;
  15. break;
  16. case "*":
  17. result = num1 * num2;
  18. break;
  19. case "/":
  20. result = num1 / num2;
  21. break;
  22. default:
  23. System.out.println("Invalid operator");
  24. }
  25. System.out.println(result);

Step-by-step explanation:

To ask for the user input for two whole numbers and an operator, we can use Java Scanner class object. Since the input operator is a string, we can use nextLine() method to get the operator string (Line 3). We use nextInt() method to get whole number input (Line 5 & 7).

Next we use the switch keyword and pass the operator into the switch structure to determine which case statement should be executed. For example, if the input operator is "*" the statement "result = num1 * num2; " will run and multiply num1 with num2.

User Sam Graham
by
5.8k points