-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
49 lines (40 loc) · 1.42 KB
/
Calculator.java
File metadata and controls
49 lines (40 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// Simple Calculator
Scanner scanner = new Scanner(System.in);
double value1;
double value2;
double result = 0;
char operator;
boolean validOperation = true;
System.out.print("Enter the first number: ");
value1 = scanner.nextDouble();
System.out.print("Enter the operator (+, -, *, /, ^): ");
operator = scanner.next().charAt(0);
System.out.print("Enter the second number: ");
value2 = scanner.nextDouble();
switch(operator) {
case '+' -> result = value1 + value2;
case '-' -> result = value1 - value2;
case '*' -> result = value1 * value2;
case '/' -> {
if(value2==0) {
System.out.println("Cannot divide by zero");
validOperation = false;
} else {
result = value1 / value2;
}
}
case '^' -> result = Math.pow(value1, value2);
default -> {
System.out.println("Invalid operator!");
validOperation = false;
}
}
if(validOperation) {
System.out.println(value1 + " " + operator + " " + value2 + " = " + result);
}
scanner.close();
}
}