Write a Java programthat can simulate a simple calculator, using the Java console as the exclusive input and output device. That is, each input to the calculator, be it a number, like 12.34 or 1034, or an operator, like + or =, can be done on a separate line. After each such input, you should output to the Java console what would be displayed on your calculator.
Program code:
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double result = 0.0;
System.out.println("Simple Calculator");
System.out.println("-----------------");
boolean exit = false;
while (!exit) {
System.out.print("Enter a number or operator (+, -, *, /, =): ");
String input = scanner.nextLine();
// Check for operators or '=' sign
if (input.equals("+") || input.equals("-") || input.equals("*") || input.equals("/")) {
// Read the next number
System.out.print("Enter the next number: ");
double number = scanner.nextDouble();
scanner.nextLine(); // Consume the newline character
// Perform the operation
switch (input) {
case "+":
result += number;
break;
case "-":
result -= number;
break;
case "*":
result *= number;
break;
case "/":
result /= number;
break;
}
} else if (input.equals("=")) {
// Display the result
System.out.println("Result: " + result);
result = 0.0;
} else {
// Convert input to a number and update the result
try {
double number = Double.parseDouble(input);
result = number;
} catch (NumberFormatException e) {
System.out.println("Invalid input!");
}
}
System.out.println(); // Print a blank line for readability
// Check if the user wants to exit
if (input.equals("exit")) {
exit = true;
}
}
System.out.println("Calculator has exited. Goodbye!");
scanner.close();
}
}
Output of the program code:
Simple Calculator
-----------------
Enter a number or operator (+, -, *, /, =): +
Enter the next number: 10
Enter a number or operator (+, -, *, /, =): 20
Enter a number or operator (+, -, *, /, =): +
Enter the next number: 200
Enter a number or operator (+, -, *, /, =): *
Enter the next number: 20
Enter a number or operator (+, -, *, /, =): =
Result: 4400.0