Dev.J

[JAVA] 문제 4-1 Interface 사칙연산 계산기 본문

Solved

[JAVA] 문제 4-1 Interface 사칙연산 계산기

JJ____ 2021. 9. 5. 20:51

 사칙연산을 하는 계산기를 완성하세요.

 calculate() : 추상메소드

 setValue() : 피연산자 설정

 

Calc 클래스

public abstract class Calc {
int a;
int b;
void setValue(int a, int b) { // 피연산자 설정 > this.a = a 를 하라는 말!
this.a = a;
this.b = b;
 }
abstract void Calculate();
}

 

Add 클래스

public class Add extends Calc {
void setValue(int a, int b) { // 피연산자 설정 > this.a = a 를 하라는 말!
this.a = a;
this.b = b;
 }
void Calculate() {
System.out.println(a + " " + b + " - " +(a + b));
}
}

 

Sub 클래스

public class Sub extends Calc {
void setValue(int a, int b) { // 피연산자 설정 > this.a = a 를 하라는 말!
this.a = a;
this.b = b;
 }
void Calculate() {
System.out.println(a + " " + b + " - " +(a - b));
}
}

 

Mul 클래스

public class Mul extends Calc {
void setValue(int a, int b) { // 피연산자 설정 > this.a = a 를 하라는 말!
this.a = a;
this.b = b;
 }
void Calculate() {
System.out.println(a + " " + b + " - " +(a * b));
}
}

 

Div 클래스

public class Div extends Calc {
void setValue(int a, int b) { // 피연산자 설정 > this.a = a 를 하라는 말!
this.a = a;
this.b = b;
 }
void Calculate() {
System.out.println(a + " " + b + " - " +(a/b));
}
}

 

CalcTest 클래스

 

import java.util.*;

 

public class CalcTest {

 

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

 

System.out.printf("두 정수와 연산자를 입력하세오. (ex. 34 5 +)");

int a = sc.nextInt(); // 숫자 1
int b = sc.nextInt(); // 숫자 2
String op = sc.next(); // operation 연산
sc.close();

 

switch (op) {
case "+":
Add add = new Add(); // 생성자
add.setValue(a, b);
add.Calculate();
break;

 

case "-":
Sub sub = new Sub(); // 생성자
sub.setValue(a, b);
sub.Calculate();
break;

 

case "*":
Mul mul = new Mul(); // 생성자
mul.setValue(a, b);
mul.Calculate();
break;

 

case "/":
Div div = new Div(); // 생성자
div.setValue(a, b);
div.Calculate();
break;
}
}
}

CalcTest 클래스_JJ

728x90