본문 바로가기

📚Study Note/JAVA

[ JAVA ] 클래스 고급 - 상속 (Inheritance) ③

// ○실습문제
//다음과 같은 프로그램을 구현한다.
//단, 상속의 개념을 적용하여 작성할 수 있도록 한다.

실행 예)
임의의 두 정수 입력(공백 구분) : 20 15
연산자 입력( + - * / ) : -
>> 20 - 15 = 5
계속하려면 아무 키나...

 

 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;


class AClass
{
	protected int x, y;
	protected char op;

	AClass()
	{
		
	}
	void write (double result)
	{
		System.out.printf(">> %d %c %d = %.2f\n", x, op, y, result);
	}

}//end AClass

class BClass extends AClass 

{	
  /*	
	protected int x, y;
	protected char op;


	void write (double result)
	{
		System.out.printf(">> %d %c %d = %.2f\n", x, op, y, result);
	}*/	

	BClass()
	{}

	boolean input() throws IOException //★ thorws IOException 의 위치 주의. 그리고 아래 main메소드 옆에도 넣어줘야함.
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("임의의 두 정수 입력(공백 구분) : ");
		String temp = br.readLine(); //"20 15" 예를 들어 
		String[] str = temp.split("\\s"); //→ 구분자 공백 
		
		// 문자열이 어떤 특정한 구분자에 의해서 나누게하겠다 라는 형태로 쓰이게 됨 
						// 문자열로 "사과 딸리 바나나 포도 수박".split(공백);
						// 이러면 배열을 반환하게 된다. {"사과", "딸기", "바나나", "포도", "수박"}

						// ex) "1 23 456 7".split(공백);
						// 문자열 형태의 배열을 반환 {"1", "23", "456", "7"}

						//==>> String[] str = {"20" , "15"};

		if (str.length !=2)
			return false; // 값의 반환 → false 그리고 메소드 종료!
			//최종적으로 false를 반환하며 메소드 종료.
			//return은 값을 반환하고 + 메소드를 종료한다.
			//※ 이 조건문을 수행할 경우 아래에 코드가 남아있는 상황이더라고
			//	 더 이상 수행하지않고 결과값을 반환하며 메소드는 종료된다. 

		x = Integer.parseInt(str[0]);
		y = Integer.parseInt(str[1]);

		System.out.print("연산자 입력(+ - * /) : ");
		op = (char)System.in.read();

		if ( op!='+' && op!='-' && op!='*' && op!='/') //★ 여기서 주의 다 부정이기에 || 가아니라 &&이어야한다.
			return false;
		return true;
		
	}// end input()

	double calc()
	{
		double result =0;

		switch (op)
		{
			case '+' : result = x+y; break;
			case '-' : result = x-y; break;
			case '*' : result = x*y; break;
			case '/' : result = (double)x/y; break;
		
		}
		return result;
	}

}//end BCLass

public class Test108
{
	public static void main(String[] args) throws IOException
	{
		BClass ob = new BClass();

		if (!ob.input())
		{
			System.out.println("Error...");
			return;
		}

		double result = ob.calc();
		ob.write(result);


	}
}//end Test108



/*
임의의 두 정수 입력(공백 구분) : 67 6
연산자 입력(+ - * /) : /
>> 67 / 6 = 11.17
계속하려면 아무 키나 누르십시오 . . .
*/