-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArithmeticOperations.java
More file actions
108 lines (93 loc) · 3.34 KB
/
ArithmeticOperations.java
File metadata and controls
108 lines (93 loc) · 3.34 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package sampleWorkout;
import java.util.InputMismatchException;
import java.util.Scanner;
public class ArithmeticOperations {
public void arithmeticOperations() {
Scanner sc = new Scanner(System.in);
double a, b;
char c;
String response;
while (true) {
System.out.print("Would you like to perform operation (yes/no): ");
response = sc.nextLine().trim().toLowerCase();
if (response.equals("no")) {
System.out.println("Exiting...");
break;
} else if(!response.equals("yes")) {
System.out.println("Invalid input. Please enter 'yes' or 'no'!!!");
continue;
}
// Read 1st operand safely
while (true) {
try {
System.out.print("Enter the 1st operand: ");
a = sc.nextDouble();
break;
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter an integer.");
sc.nextLine(); // clear buffer
}
}
// Read operator safely
while (true) {
try {
System.out.print("Enter the operator (+, -, *, /, %): ");
c = sc.next().charAt(0);
if ("+-*/%".indexOf(c) != -1) {
break;
} else {
System.out.println("Invalid operator. Try again.");
}
} catch (Exception e) {
System.out.println("Invalid input for operator.");
sc.nextLine();
}
}
// Read 2nd operand safely
while (true) {
try {
System.out.print("Enter the 2nd operand: ");
b = sc.nextDouble();
break;
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter an integer.");
sc.nextLine(); // clear buffer
}
}
sc.nextLine(); // consume newline
try {
Double result = calculate(a, b, c);
if (result != null) {
System.out.printf("Result: %.2f %c %.2f = %.2f\n", a, c, b, result);
}
}catch (Exception e) {
System.out.println(e.getMessage());
sc.nextLine();
}
System.out.println(); // add space before next round
}
sc.close();
}
public static Double calculate(double a, double b, char c) {
switch (c) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/':
if (b == 0) {
System.out.println("Cannot divide by zero!");
return null;
}
return a / b;
case '%':
if (b == 0) {
System.out.println("Cannot mod by zero!");
return null;
}
return a % b;
default:
System.out.println("Unknown operator!");
return null;
}
}
}