Write a Java Program to make a simple calculator using switch statement.
Click Here to View the Solution!
public static void main(String args)
Scanner reader =new
System.out.print("Enter two numbers: "
);// nextDouble() reads next double from the keyboard and store them as double
firstNum = reader.nextDouble();
secondNum = reader.nextDouble();
System.out.print("Enter an operator (+, -, *, /): "
operator = reader.next().charAt(0
result = firstNum + secondNum;
result = firstNum - secondNum;
result = firstNum * secondNum;
result = firstNum / secondNum;
// If statement to check operator doesn't match any case constant(+, -, *, /)
System.out.printf("Error! Please choose a valid operator"
System.out.println(firstNum +" "
+ operator +" "
+ secondNum +" = "
Click Here to View the Output!
Enter two numbers: 4 7 Enter an operator (+, -, *, /): * 4.0 * 7.0 = 28.0
Click Here to View the Explanation!
- This program is used to create a simple calculator by using a
switch…casemethod in Java.
- The calculator will be able to calculate simple mathematical operations, addition, subtraction, multiplication and division between two values.
- Initially, the program will request the user to enter two numbers. These two numbers ‘4’ and ‘7’ will be stored in two different variables ‘
firstNum’ and ‘
secondNum’ through the
nextDouble()method of the scanner object.
- Then the program will request the user to select one of the operators from the displayed options, ‘
+, -,*,/’ which are stated in the program in 4 separate cases. This operator will be stored in the variable ‘operator’ through the
next()method of the scanner object.
- After the user enters the character ‘*’, the control shifts to the case ‘*’ where the operation ‘result =
firstNum * secondNum’ exists.
- This operation will calculate the product of the two number
secondNumand store their output in the variable result. After the operation is carried out, the break statement will end the switch statement.
- An exception is included in the program at the end of the switch statement that if the user enters any character except for the operator characters mentioned in the cases, then display the error message using
- Lastly, the operation statement will be displayed with the result.