-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.java
105 lines (92 loc) · 2.79 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
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
import java.util.Scanner;
class SQRT_exception extends Exception {
SQRT_exception(String s) {
super(s);
}
}
public class calculator {
public int add() {
Scanner input = new Scanner(System.in);
int x, y;
System.out.println("enter numbers!");
x = input.nextInt();
y = input.nextInt();
return x + y;
}
public int circumstance() {
Scanner input = new Scanner(System.in);
int x, y;
System.out.println("enter numbers!");
x = input.nextInt();
y = input.nextInt();
return x - y;
}
public int multiply() {
Scanner input = new Scanner(System.in);
int x, y;
System.out.println("enter numbers!");
x = input.nextInt();
y = input.nextInt();
return x * y;
}
public int division() {
Scanner input = new Scanner(System.in);
int x, y;
System.out.println("enter numbers!");
x = input.nextInt();
y = input.nextInt();
if (y == 0) {
throw new ArithmeticException("division by zero is not required");
} else {
return x / y;
}
}
public int SQRT() throws SQRT_exception {
Scanner input = new Scanner(System.in);
int x;
System.out.println("enter number!");
x = input.nextInt();
if (x < 0) {
throw new SQRT_exception("invalid number's format");
} else {
return (int) Math.sqrt(x);
}
}
}
class Main {
public static void main(String[] args) {
calculator c = new calculator();
while (true) {
System.out.println("which operator do you want?\n1)add\n2)circumstance\n3)multiply\n4)division\n5)SQRT\n6)exit");
Scanner in = new Scanner(System.in);
int answer = in.nextInt();
switch (answer) {
case 1:
System.out.println(c.add());
break;
case 2:
System.out.println(c.circumstance());
break;
case 3:
System.out.println(c.multiply());
break;
case 4:
try {
System.out.println(c.division());
} catch (ArithmeticException e) {
System.out.println("exception handled " + e);
}
break;
case 5:
try {
System.out.println(c.SQRT());
} catch (SQRT_exception e) {
System.out.println("exception handled " + e);
}
break;
case 6:
return;
}
}
}
}