The simple calculator expects user input for the arithmetic operation, and for the two numbers that are to be calculated together. Depending on the arithmetic symbol, a switch statement is used to decide which arithmetic operation is to be performed.
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double firstNumber, secondNumber, result = 0.0;
char arithmeticOperation;
System.out.print("Please enter an arithmetic operation (+, -, *, /): ");
arithmeticOperation = scan.next().charAt(0);
System.out.print("Please enter your first number: ");
firstNumber = scan.nextInt();
System.out.print("Please enter your second number: ");
secondNumber = scan.nextInt();
switch (arithmeticOperation) {
case '+' :
result = firstNumber + secondNumber;
break;
case '-' :
result = firstNumber - secondNumber;
break;
case '*' :
result = firstNumber * secondNumber;
break;
case '/' :
result = firstNumber / secondNumber;
break;
default:
System.out.print("Unknown arithmetic symbol");
}
System.out.print(firstNumber + " " + arithmeticOperation + " " + secondNumber + " = " + result);
}
}
Please enter an arithmetic operation (+, -, *, /): -
Please enter your first number: 34
Please enter your second number: 23
34.0 - 23.0 = 11.0
Here’s a detailed explanation of the code:
Scanner
class to read input from the user.import java.util.Scanner;
SimpleCalculator
class with a main
method.public class SimpleCalculator {
public static void main(String[] args) {
Scanner
object to read input from the user.Scanner scan = new Scanner(System.in);
double
variables to hold the first number, second number, and result of the calculation.double firstNumber, secondNumber, result = 0.0;
char
variable to hold the arithmetic operation entered by the user.char arithmeticOperation;
Scanner
object.System.out.print("Please enter an arithmetic operation (+, -, *, /): ");
arithmeticOperation = scan.next().charAt(0);
Scanner
object.System.out.print("Please enter your first number: ");
firstNumber = scan.nextInt();
Scanner
object.System.out.print("Please enter your second number: ");
secondNumber = scan.nextInt();
switch
statement to determine which arithmetic operation was selected and perform the appropriate calculation. switch (arithmeticOperation) {
case '+' :
result = firstNumber + secondNumber;
break;
case '-' :
result = firstNumber - secondNumber;
break;
case '*' :
result = firstNumber * secondNumber;
break;
case '/' :
result = firstNumber / secondNumber;
break;
default:
System.out.print("Unknown arithmetic symbol");
}
System.out.print
.System.out.print(firstNumber + " " + arithmeticOperation + " " + secondNumber + " = " + result);