File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
src/test/java/com/thealgorithms/maths/Calculator Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+ class public SimpleCalculator {
4
+ public static void main (String [] args ) {
5
+ Scanner in = new Scanner (System .in );
6
+
7
+ System .out .println ("""
8
+ ===== Simple Calculator =====
9
+ 1. Addition
10
+ 2. Subtraction
11
+ 3. Multiplication
12
+ 4. Division
13
+ 5. Exit
14
+ Enter your choice: """ );
15
+
16
+ int choice = in .nextInt ();
17
+
18
+ switch (choice ) {
19
+ case 1 : performOperation (in , '+' );
20
+ case 2 : performOperation (in , '-' );
21
+ case 3 : performOperation (in , '*' );
22
+ case 4 : performOperation (in , '/' );
23
+ case 5 : System .out .println ("Exiting..." );
24
+ default : System .out .println ("Invalid choice! Please select between 1-5." );
25
+ }
26
+
27
+ in .close ();
28
+ }
29
+
30
+ private static void performOperation (Scanner in , char operator ) {
31
+ System .out .print ("Enter 2 numbers: " );
32
+ int a = in .nextInt ();
33
+ int b = in .nextInt ();
34
+ int result = 0 ;
35
+
36
+ switch (operator ) {
37
+ case '+' : result = a + b ;
38
+ case '-' : result = a - b ;
39
+ case '*' : result = a * b ;
40
+ case '/' : {
41
+ if (b != 0 ) {
42
+ result = a / b ;
43
+ } else {
44
+ System .out .println ("Error: Division by zero!" );
45
+ return ;
46
+ }
47
+ }
48
+ }
49
+ System .out .println ("Result: " + result );
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments