public abstract class Calc {
protected int a;
protected int b;
void setValue(int a,int b) {
this.a = a;
this.b = b;
}
abstract int calculate();
}
import java.util.Scanner;
class Add extends Calc{
@Override
int calculate() {
return a+b;
}
}
class Sub extends Calc{
@Override
int calculate() {
// TODO Auto-generated method stub
return a-b;
}
}
class Mul extends Calc{
@Override
int calculate() {
// TODO Auto-generated method stub
return a*b;
}
}
class Div extends Calc{
@Override
int calculate() {
// TODO Auto-generated method stub
return a/b;
}
}
public class ex11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.print("두 정수와 연산자를 입력하시오>>");
int a = sc.nextInt();
int b = sc.nextInt();
String op = sc.next();
Calc c;
switch(op) {
case "+":
c = new Add();
break;
case "-":
c = new Sub();
break;
case "*":
c = new Mul();
break;
case "/":
c = new Div();
break;
default :
System.out.println("잘못된 연산자입니다.");
sc.close();
return;
}
c.setValue(a, b);
if(c instanceof Div && b==0) {
System.out.println("계산할 수 없습니다.");
}
else {
System.out.println(c.calculate());
}
sc.close();
}
}
결과
두 정수와 연산자를 입력하시오>>1 2 +
3
두 정수와 연산자를 입력하시오>>2 0 /
계산할 수 없습니다.
'명품JAVA프로그래밍 > 5장 상속' 카테고리의 다른 글
[명품JAVA프로그래밍] 5장 실습문제 13번 (0) | 2022.01.17 |
---|---|
[명품JAVA프로그래밍] 5장 실습문제 12번 (0) | 2022.01.17 |
[명품JAVA프로그래밍] 5장 실습문제 10번 (0) | 2022.01.13 |
[명품JAVA프로그래밍] 5장 실습문제 9번 (0) | 2022.01.13 |
[명품JAVA프로그래밍] 5장 실습문제 8번 (0) | 2022.01.12 |