-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.java
57 lines (52 loc) · 2.35 KB
/
calculator.java
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
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("-------------------------Calculator-------------------------");
System.out.println("");
try {
System.out.println("Enter the first number");
int num1 = sc.nextInt();
System.out.println("Enter the Second Number");
int num2 = sc.nextInt();
System.out.println("Select the Operator: '+' , '-' , '*' , '/' , '%' ");
char op = sc.next().charAt(0);
switch (op) {
case '+':
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
System.out.println("");
break;
case '-':
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
System.out.println("");
break;
case '*':
System.out.println(num1 + " * " + num2 + " = " + (num1 * num2));
System.out.println("");
break;
case '/':
if (num2 != 0) {
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
System.out.println("");
} else {
System.out.println("Cannot divide by zero. Please enter a non-zero second number.");
System.out.println("");
}
break;
case '%':
System.out.println(num1 + " % " + num2 + " = " + (num1 % num2));
System.out.println("");
break;
default:
System.out.println("Enter a valid operator");
System.out.println("");
break;
}
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid input. Please enter a valid number.");
sc.next();
}
}
}
}