📚 Study/Java
JAVA :: Test113_상속(상속의 개념을 적용하여 연산 프로그램 구현)
bono-hye
2023. 9. 14. 23:09
○ 실습
다음과 같은 프로그램을 구현한다.
단, 상속의 개념을 적용하여 작성할 수 있도록 한다.
실행 예)
임의의 두 정수 입력(공백 구분) : 20 10
연산자 입력 (+ - * /) : -
>> 20 - 10 = 10.00
계속하려면 아무 키나 누르세요...
▼ 내가 작성한 코드
import java.util.Scanner;
import java.io.IOException;
class Aclass
{
protected int x, y;
protected char op;
Aclass()
{
}
void write(double result)
{
System.out.printf("\n>> %d %c %d = %.2f\n", x, op, y, result);
}
}
// Aclass 를 상속받는 클래스로 설계
class Bclass extends Aclass
{
void input() throws IOException
{
Scanner sc = new Scanner(System.in);
System.out.print("임의의 두 정수 입력(공백 구분) : ");
x = sc.nextInt();
y = sc.nextInt();
System.out.print("연산자 입력(+ - * /) : ");
op = (char)System.in.read();
}
void calc()
{
double result = 0;
if (op=='+')
{
result = (double)x+y;
}
if (op=='-')
{
result = (double)x-y;
}
if (op=='*')
{
result = (double)x*y;
}
if (op=='/')
{
result = (double)x/y;
}
write(result);
}
}
// main() 메소드를 포함하고 있는 외부의 다른 클래스 (Bclass 기반으로 실행 예 나오게)
public class Test113
{
public static void main(String[] args) throws IOException
{
Bclass ob = new Bclass();
ob.input();
ob.calc();
}
}