SimpleCalculator.java Write a program that can serve as a simple calculator. Thi
ID: 3627360 • Letter: S
Question
SimpleCalculator.javaWrite a program that can serve as a simple calculator. This calculator keeps track of a single number (of type double) that is called result and that starts out as 0.0. Each cycle allows the user to repeatedly add, subtract, multiply, or divide by a second number. The result of one of these operations becomes the new value of result. The calculation ends when the user enters the letter R for “result” (either in uppercase or lowercase). The user is allowed to do another calculation from the beginning as often as he or she wants. Use the Scanner for input.
The input format is shown in the following sample dialog. If the user enters any operator symbol other than +, -, *, or /, then display “an UnknownOperatorException is thrown “and the user is asked to reenter that line of input.
Calculator is on.
result = 0.0
+5
result + 5.0 = 5.0
new result = 5.0
*2.2
result * 2.2 = 11.0
updated result = 11.0
% 10
% is an unknown operation
Reenter, your last line:
* 0.1
result * 0.1 = 1.1
uptdated result = 1.1
r
Final result = 1.1
Again? (y/n)
yes
result = 0.0
+10
result + 10.0 =10.0
new result = 10.0
/2
result / 2.0 = 5.0
updated result = 5.0
r
Final result = 5.0
Again? (y/n)
N
End of Program
Explanation / Answer
import java.util.*; public class SimpleCalculator { private static double result = 0.0; public static void main(String[] args) { Scanner input = new Scanner(System.in); intro(); program(input); } public static void program(Scanner input) { String console = input.next().toLowerCase(); while(!console.equals("r")) { char symbol = console.charAt(0); double number = Double.parseDouble(console.substring(1)); performCalculation(symbol, number); console = input.next().toLowerCase(); } System.out.println("final result = " + result); System.out.println("Again? (y/n)"); String again = input.next().toLowerCase(); if(again.equals("y")) { intro(); program(input); } else { System.out.println("end of program"); } } public static void printResult(char symbol, double number) { System.out.println("result " + symbol + " " + number + " = " + result); System.out.println("updated result = " + result); } public static void performCalculation(char symbol, double number) { if(symbol == '+') { result += number; printResult(symbol, number); } else if (symbol == '-') { result -= number; printResult(symbol, number); } else if(symbol == '*') { result *= number; printResult(symbol, number); } else if (symbol == '/') { result /= number; printResult(symbol, number); } else { System.out.println(symbol + " is an unknown operation"); System.out.println("Reenter your last line:"); } } public static void intro() { System.out.println("Calculator is on. result = 0.0"); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.