-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleCalculator.java
More file actions
22 lines (21 loc) · 866 Bytes
/
Copy pathSimpleCalculator.java
File metadata and controls
22 lines (21 loc) · 866 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class SimpleCalculator {
public static void main(String[] args) {
double a = 20, b = 4;
System.out.println(a + " + " + b + " = " + calculate(a, b, '+'));
System.out.println(a + " - " + b + " = " + calculate(a, b, '-'));
System.out.println(a + " * " + b + " = " + calculate(a, b, '*'));
System.out.println(a + " / " + b + " = " + calculate(a, b, '/'));
}
static double calculate(double a, double b, char operator) {
switch (operator) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/':
if (b == 0) throw new ArithmeticException("Division by zero");
return a / b;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
}