Simple Calculator
Problem
Read a line a op b where a and b are non-negative integers and op is one of + - * / %. Print the result. For + - * % print a whole number. For / print the decimal result with 2 digits after the dot. If b is 0 for / or %, print Cannot divide by zero. For any other operator print Invalid operator.
Constraints
- 0 <= a, b <= 10^9
Examples
Input
10 / 4
Output
2.50
Input
5 / 0
Output
Cannot divide by zero
Solutions
A switch (or an if / elif chain) selects the operation. We check division by zero before we divide. For the decimal result of a division we must use decimal numbers, and Java needs an explicit cast to double.
/*
* Problem : Do a calculation with two numbers and an operator.
* Input : Two integers and one operator on one line: a op b.
* Output : The result, or an error message.
* Approach: Choose the operation with a switch statement.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long first = scanner.nextLong();
char operator = scanner.next().charAt(0);
long second = scanner.nextLong();
// Step 1: A switch statement chooses one case by the value of the operator.
switch (operator) {
case '+':
System.out.println(first + second);
break; // break stops the switch. Without it Java would continue with the next case.
case '-':
System.out.println(first - second);
break;
case '*':
System.out.println(first * second);
break;
case '/':
// Step 2: Dividing by zero is not allowed, so we check the second number first.
if (second == 0) {
System.out.println("Cannot divide by zero");
} else {
// Step 3: Convert to double so the division keeps the decimal part. Example: 10 / 4 = 2.5.
System.out.println(String.format(Locale.US, "%.2f", (double) first / second));
}
break;
case '%':
if (second == 0) {
System.out.println("Cannot divide by zero");
} else {
System.out.println(first % second);
}
break;
// Step 4: default runs when no case matches.
default:
System.out.println("Invalid operator");
}
}
}
Hints (2)
- What happens when you divide by 0?
- Why does Java need a cast to double?