English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to create a simple calculator using the switch..case statement in Java. The calculator will be able to perform addition, subtraction, multiplication, and division on two numbers.
import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter two numbers: "); //nextDouble() reads the next double from the keyboard double first = reader.nextDouble(); double second = reader.nextDouble(); +, -, *, / char operator = reader.next().charAt(0); double result; switch(operator) { case '+': result = first + second; break; case '-': result = first - second; break; case '*': result = first * second; break; case '/': result = first / second; break; // operator does not match (+, -, *, /) default: System.out.printf("Error! operator is not correct"); return; } System.out.printf("%.2f", first, operator, second, result);1f %c %.2f1f = %.2f1f", first, operator, second, result); } }
When running the program, the output is:
Enter two numbers 1.5 4.5 Enter an operator (+, -, *, /) : * 1.5 * 4.5 = 6.8
User input*The operator is stored in the operator variable using the next() method of the Scanner object.
Similarly, use the nextDouble() method of the Scanner object to take two operands1.5and4.5are stored in the variables first and second separately.
because the operator*with condition case '*'matches: Therefore, the program control jumps to
result = first * second;
The statement calculates the result and stores it in the variable result, and then break; ends the switch statement.
Finally, the printf statement is executed.
Note: We use the printf() method instead of println. This is because we want to print a formatted string. For more information, please visitJava printf() Method.