import java.util.Scanner; public class Calculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter first number:"); double num1 = scanner.nextDouble(); System.out.println("Enter second number:"); double num2 = scanner.nextDouble(); System.out.println("Enter an operator (+, -, *, /): "); String operator = scanner.next(); double result; switch (operator) { case "+": result = num1 + num2; break; case "-": result = num1 - num2; break; case "*": result = num1 * num2; break; case "/": if (num2 != 0) { result = num1 / num2; } else { System.out.println("Cannot divide by zero!"); return; } break; default: System.out.println("Invalid operator!"); return; } System.out.println("The result is: " + result); } }
In this example, the Scanner
class is used to take input from the user. The program prompts the user to enter two numbers and an operator, and then performs the appropriate calculation based on the operator entered by the user.
The program uses a switch statement to evaluate the operator and to perform the corresponding calculation.
It also checks the second number for division operation if it’s not equal to zero if yes, it will return Cannot divide by zero! to the user.
This is a very simple example of a calculator. You can further enhance it to handle more complex operations and to improve error handling and input validation.