-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
75 lines (60 loc) · 2.13 KB
/
Calculator.java
File metadata and controls
75 lines (60 loc) · 2.13 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
import java.util.Scanner;
public class Calculator {
// Method for Addition
public static double add(double a, double b) {
return a + b;
}
// Method for Subtraction
public static double subtract(double a, double b) {
return a - b;
}
// Method for Multiplication
public static double multiply(double a, double b) {
return a * b;
}
// Method for Division with divide-by-zero check
public static double divide(double a, double b) {
if (b == 0) {
System.out.println("Error: Cannot divide by zero!");
return Double.NaN;
}
return a / b;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueCalc = true;
System.out.println("===== Java Console Calculator =====");
while (continueCalc) {
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
System.out.println("Choose operation: + - * /");
char operator = scanner.next().charAt(0);
double result = 0;
switch (operator) {
case '+':
result = add(num1, num2);
break;
case '-':
result = subtract(num1, num2);
break;
case '*':
result = multiply(num1, num2);
break;
case '/':
result = divide(num1, num2);
break;
default:
System.out.println("Invalid operator!");
continue;
}
System.out.println("Result: " + result);
System.out.print("Do you want to perform another calculation? (yes/no): ");
String response = scanner.next().toLowerCase();
continueCalc = response.equals("yes");
}
System.out.println("Thank you for using the calculator!");
scanner.close();
}
}