-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCalculator(java)
80 lines (76 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package javadoc;
import java.util.InputMismatchException;
import java.util.Scanner;
abstract class Calc{
int a;
int b;
void setValue(int a,int b){
this.a=a;
this.b=b;
}
abstract int calculate();
}
class Add extends Calc{
int calculate() {
return (a+b);
}
}
class Sub extends Calc{
int calculate() {
return (a-b);
}
}
class Mul extends Calc{
int calculate() {
return (a*b);
}
}
class Div extends Calc{
int calculate() {
return (a/b);
}
}
public class week6_2 {
public static void main(String[] args) {
while (true) {
System.out.println("두 정수와 연산자를 입력(종료를 희망하시면 999를 입력해주세요.)");
Scanner sc = new Scanner(System.in);
try { // 정수 입력 예외처리
int a = sc.nextInt();
if (a == 999) {
System.out.print("프로그램을 종료합니다.");
return;
} else {
int b = sc.nextInt();
try {
Calc expr = null;
char oper = sc.next().charAt(0);
switch (oper) {
case '+':
expr = new Add();
break;
case '-':
expr = new Sub();
break;
case '*':
expr = new Mul();
break;
case '/':
expr = new Div();
break;
}
int answer;
expr.setValue(a, b);
answer = expr.calculate();
System.out.println(answer + " 입니다.");
} catch (NullPointerException e) { // 연산자 오류
System.out.println("피연산자 두개와 연산자(+ - * /) 순서로 입력하세요.");
}
}
}
catch(InputMismatchException e) { // 정수 입력 오류
System.out.println("정수를 입력하세요!");
}
}
}
}