Challenge: Simple Calculator
Completed
Read a number, an operator (+, -, * or /) and another number, and print the result. Use switch. If the operator is / and the second number is 0, print Cannot divide by zero. For any other operator print Unknown operator.
Input
One line: a op b, e.g. 8 / 2. a and b are whole numbers.
Output
The result as a whole number (use integer division), or one of the messages.
Example
Input
8 / 2
Output
4
Editor
Java
Hints
Read the operator with sc.next() as a String.
switch works on Strings: case "+":
Don't forget break after each case.
Solution explanation
The switch picks the operation, and an if inside the "/" case guards against dividing by zero.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
String op = sc.next();
int b = sc.nextInt();
switch (op) {
case "+":
System.out.println(a + b);
break;
case "-":
System.out.println(a - b);
break;
case "*":
System.out.println(a * b);
break;
case "/":
if (b == 0) {
System.out.println("Cannot divide by zero");
} else {
System.out.println(a / b);
}
break;
default:
System.out.println("Unknown operator");
}
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module