-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculator.java
More file actions
60 lines (45 loc) · 1.63 KB
/
calculator.java
File metadata and controls
60 lines (45 loc) · 1.63 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
50
51
52
53
54
55
56
57
58
59
60
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("\n----- SIMPLE CALCULATOR -----");
System.out.print("Enter first number (or type exit): ");
String input1 = sc.next();
if (input1.equalsIgnoreCase("exit")) {
System.out.println("Calculator closed. Goodbye!");
break;
}
double num1 = Double.parseDouble(input1);
System.out.print("Enter second number: ");
double num2 = sc.nextDouble();
System.out.print("Choose operation (+, -, *, /): ");
String op = sc.next();
double result = 0;
switch (op) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
System.out.println("Error: Cannot divide by zero!");
continue;
}
result = num1 / num2;
break;
default:
System.out.println("Invalid operator! Use + - * /");
continue;
}
System.out.println("Result: " + result);
System.out.println("Type 'exit' anytime to stop.\n");
}
sc.close();
}
}