forked from waboke/calculator_app_java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwingCalculator.java
More file actions
83 lines (71 loc) · 2.84 KB
/
SwingCalculator.java
File metadata and controls
83 lines (71 loc) · 2.84 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
72
73
74
75
76
77
78
79
80
81
82
83
import java.util.Scanner;
import java.util.InputMismatchException;
public class ConsoleCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean running = true;
System.out.println("Java Console Calculator");
System.out.println("=======================");
while (running) {
displayMenu();
int choice = getIntInput(scanner, "Enter your choice: ");
if (choice == 5) {
running = false;
System.out.println("Exiting calculator. Goodbye!");
continue;
}
if (choice < 1 || choice > 4) {
System.out.println("Invalid choice! Please try again.");
continue;
}
double num1 = getDoubleInput(scanner, "Enter first number: ");
double num2 = getDoubleInput(scanner, "Enter second number: ");
performOperation(choice, num1, num2);
}
scanner.close();
}
private static void displayMenu() {
System.out.println("\nAvailable operations:");
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");
}
private static void performOperation(int choice, double num1, double num2) {
switch (choice) {
case 1 -> System.out.printf("Result: %.2f + %.2f = %.2f%n", num1, num2, num1 + num2);
case 2 -> System.out.printf("Result: %.2f - %.2f = %.2f%n", num1, num2, num1 - num2);
case 3 -> System.out.printf("Result: %.2f * %.2f = %.2f%n", num1, num2, num1 * num2);
case 4 -> {
if (num2 == 0) {
System.out.println("Error: Cannot divide by zero!");
} else {
System.out.printf("Result: %.2f / %.2f = %.2f%n", num1, num2, num1 / num2);
}
}
}
}
private static int getIntInput(Scanner scanner, String prompt) {
while (true) {
try {
System.out.print(prompt);
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter an integer.");
scanner.nextLine(); // Clear invalid input
}
}
}
private static double getDoubleInput(Scanner scanner, String prompt) {
while (true) {
try {
System.out.print(prompt);
return scanner.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a number.");
scanner.nextLine(); // Clear invalid input
}
}
}
}