This repository was archived by the owner on Jun 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathSimple_calci.java
More file actions
71 lines (65 loc) · 2.51 KB
/
Simple_calci.java
File metadata and controls
71 lines (65 loc) · 2.51 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
61
62
63
64
65
66
67
68
69
70
71
import java.util.Scanner;
public class Simple_calci {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean exit = false;
while (!exit) {
showMenu();
int choice = scanner.nextInt();
switch (choice) {
case 1:
performOperation(scanner, "add");
break;
case 2:
performOperation(scanner, "subtract");
break;
case 3:
performOperation(scanner, "multiply");
break;
case 4:
performOperation(scanner, "divide");
break;
case 5:
exit = true;
System.out.println("Exiting the calculator. Goodbye!");
break;
default:
System.out.println("Invalid choice. Please try again.");
}
}
scanner.close();
}
private static void showMenu() {
System.out.println("\n--- Basic Calculator ---");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
}
private static void performOperation(Scanner scanner, String operation) {
System.out.print("Enter the first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter the second number: ");
double num2 = scanner.nextDouble();
switch (operation) {
case "add":
System.out.printf("Result: %.2f + %.2f = %.2f\n", num1, num2, num1 + num2);
break;
case "subtract":
System.out.printf("Result: %.2f - %.2f = %.2f\n", num1, num2, num1 - num2);
break;
case "multiply":
System.out.printf("Result: %.2f * %.2f = %.2f\n", num1, num2, num1 * num2);
break;
case "divide":
if (num2 != 0) {
System.out.printf("Result: %.2f / %.2f = %.2f\n", num1, num2, num1 / num2);
} else {
System.out.println("Error: Division by zero is not allowed.");
}
break;
}
}
}