33일차

김윤정·2024년 8월 1일

코딩

목록 보기
33/60
post-thumbnail

1. 과일, 사과, 배, 포도를 표현한 클래스를 만들고 이들 간의 관계를 고려하여 하나의 클래스를 추상 클래스로 만들어 메소드 print()를 구현하고 다음과 같은 소스와 결과가 나오도록 클래스를 작성하시오.

소스
Fruit fAry[] = {new Grape(), new Apple(), new Pear());
for(Fruit f : fAry)
f.print();
-- 결과 --
나는 포도이다.
나는 사과이다.
나는 배이다.

package day_2024_08_01;

interface IFruit {
	public abstract void print();
}

class Grape implements IFruit {

	@Override
	public void print() {
		System.out.println("나는 포도이다");
	}

}

class Apple implements IFruit {

	@Override
	public void print() {
		System.out.println("나는 사과이다");
	}

}

class Pear implements IFruit {

	@Override
	public void print() {
		System.out.println("나는 배이다");
	}

}

public class InterfaceFruitMain {

	public static void main(String[] args) {
		IFruit fAry[] = { new Grape(), new Apple(), new Pear() };
		for (IFruit f : fAry)
			f.print();

	}

}

2. 아래가 돌아 가도록 하시오.

interface ICalculator{
int add(int num1,int num2);
int sub(int num1,int num2);
int mul(int num1,int num2);
int div(int num1,int num2);
}
public static void main(String[] args) {
ICalculator calculator = new MyCalculator();
System.out.println(calculator.add(0, 0)); //0
System.out.println(calculator.sub(1, 1)); //0
System.out.println(calculator.mul(0, 0)); //0
System.out.println(calculator.div(1, 1)); //0
}

package day_2024_08_01;

interface ICalculater {
	int add(int num1, int num2);

	int sub(int num1, int num2);

	int mul(int num1, int num2);

	int div(int num1, int num2);
}

class MyCalculater implements ICalculater {

	@Override
	public int add(int num1, int num2) {

		return num1 + num2;
	}

	@Override
	public int sub(int num1, int num2) {

		return num1 - num2;
	}

	@Override
	public int mul(int num1, int num2) {

		return num1 * num2;
	}

	@Override
	public int div(int num1, int num2) {
		if (num2 == 0) {
			System.out.println("잘못된 입력입니다");
			return 0;
		}
		return num1 / num2;
	}

}

public class InterfaceExampleMain {

	public static void main(String[] args) {
		ICalculater calculator = new MyCalculater();
		System.out.println(calculator.add(0, 0)); // 0
		System.out.println(calculator.sub(1, 1)); // 0

	}

}

3. 아래의 코드를 완성 하시오.

abstract class Calc {
protected int a;
protected int b;
public void setValue(int a, int b) {
this.a = a;
this.b = b;
}
abstract int calculate() ;
}
main(){
Scanner sc = new Scanner(System.in);
int result=0;
System.out.print("두 정수와 연산자를 입력하시오 >> ");
int a = sc.nextInt(); //5
int b = sc.nextInt(); //7
String str = sc.next(); //+-/
char c = str.charAt(0);
Calc cal;
switch(c) {
case '+' :
cal = new Add();
break;
case '-' :
cal = new Sub();
break;
case '
' :
cal = new Mul();
break;
case '/' :
cal = new Div();
break;
default :
System.out.println("잘못된 연산자 입니다.");
sc.close();
return;
}
cal.setValue(a, b);
result = cal.calculate();
System.out.println(result);
sc.close();
}

package day_2024_08_01;

import java.util.Scanner;

abstract class Calc {
	   protected int a;
	   protected int b;
	   public void setValue(int a, int b) {
	      this.a = a;
	      this.b = b;
	   }
	   abstract int calculate();
	}

class Add extends Calc{

	@Override
	int calculate() {
	
		return a+ b;
	}
	
}

class Sub extends Calc{

	@Override
	int calculate() {
	
		return a-b;
	}
	
}

class Mul extends Calc{

	@Override
	int calculate() {
	
		return a*b;
	}
	
}
class Div extends Calc{

	@Override
	int calculate() {
		if(b==0) {
			System.out.println("잘못된 입력입니다");
			return 0;
		}
		return a/b;
	}
	
}


public class ExampleMain {

	public static void main(String[] args) {
		
	      Scanner sc = new Scanner(System.in);
	      int result=0;
	      System.out.print("두 정수와 연산자를 입력하시오 >> ");
	      int a = sc.nextInt();
	      int b = sc.nextInt();
	      char c = sc.next().charAt(0); //sc.next가 스트링으로 char 배열이다,  +-*/에서 0번째
	      Calc cal;
	      switch(c) {
	      case '+' : 
	         cal = new Add();
	         break;
	      case '-' :
	         cal = new Sub();
	         break;
	      case '*' :
	         cal = new Mul();
	         break;
	      case '/' :
	         cal = new Div();
	         break;
	      default :
	         System.out.println("잘못된 연산자 입니다.");
	         sc.close();
	         return;
	      }
	      cal.setValue(a, b);
	      result = cal.calculate();
	      System.out.println(result);
	      sc.close();

	}

}

4. throws 에 대하여 설명하시오.(예습)

메소드 내에서 문장을 실행하는 과정에서 해당 에러가 발생할 수 있다는 의미로 아래에 해당할때 사용합니다

  • 메서드 내부에서 사용.
  • 직접 예외를 발생시킬 때 사용.

5. checked 와 unckecked Excetpion 을 설명하시오.(예습)

Exception의 subclass인 unchecked Exception은(= RuntimeException) 예외 처리를 해야 한다고 강제하지 않습니다. (런타임에 체크)

하지만 Exception의 subclass인 checked Exception은 반드시 프로그래머가 예외 처리를 해야 한다. (컴파일 타임에 체크)
예외 처리를 하지 않으면 프로그램 작성중에 이미 빨간줄로 에러 표시가 떠서 진행할 수가 없게 됩니다.

6. try catch finally 에 대하여 예를 들어 설명하시오.

try catch finally는 예외 처리의 기본적인 문장 구성입니다.

실행의 흐름이 try 구문 안에 들어왔을 때 반드시 실행 해야 하는 문장을 finally 구문에 둘 수 있습니다.

try 구문안에 오류가 나면 잡아주는게 catch 구문입니다.

finally는 앞의 try-catch에서 에러가 나든 안나든 무조건 타게 되어있습니다.

7. 아래가 컴파일 에러가 나는 이유에 대하여 설명하시오.

try {
int num = 6 / 0;
} catch (Exception e) {
e.printStackTrace();
} catch (InputMismatchException e) {
e.printStackTrace();
}

Exception이 InputMismatchException보다 상위 클래스에 위치하고 있으므로 모든 예외 상황을 체크할 수 있습니다.
그래서 여기에서 모든 예외가 처리 되기 때문에 세부 체크를 하는 InputMismatchException이나ArithmeticException 등이 그 아래 catch로 온다면 사실상 그 문장을 통과할 일이 없기 때문에 불필요한 코드임을 알려주기 위해 에러가 납니다.

8. 다음 조건을 만족하도록 클래스 Person과 Student를 작성하시오.

  • 클래스 Person
  • 필드 : 이름, 나이, 주소 선언
  • 클래스 Student
  • 필드 : 학교명, 학과, 학번, 8개 평균평점을 저장할 배열로 선언
  • 생성자 : 학교명, 학과, 학번 지정
  • 메소드 average() : 8개 학기 평균평점의 평균을 반환
  • 클래스 Person과 Student
  • 프로그램 테스트 프로그램의 결과 : 8개 학기의 평균평점은 표준입력으로 받도록한다.
  • 에러가 날만한 곳은 try-catch로 처리.
    이름 : 김다정
    나이 : 20
    주소 : 서울시 관악구
    학교 : 동양서울대학교
    학과 : 전산정보학과
    학번 : 20132222

8학기 학점을 순서대로 입력하세요
1학기 학점 → 3.37
2학기 학점 → 3.89
3학기 학점 → 4.35
4학기 학점 → 3.76
5학기 학점 → 3.89
6학기 학점 → 4.26
7학기 학점 → 4.89
8학기 학점 → 3.89


8학기 총 평균 평점은 4.0375점입니다.
힌트)
public static void main(String[] args) {
Student stu = new Student("김다정", 20, "서울시", "동양서울대학교", "전산정보학과", 20132222);
stu.showInfo();
stu.average();
}

package day_2024_08_01;

import java.util.InputMismatchException;

import java.util.Scanner;

class Person {
	String name;
	int age;
	String addr;

	Person(String name, int age, String addr) {
		this.name = name;
		this.age = age;
		this.addr = addr;
	}

	public void showInfo() {
		System.out.println("이름 " + this.name);
		System.out.println("나이 " + this.age);
		System.out.println("주소 " + this.addr);
	}

}

class Student extends Person {
	String school;
	String major;
	int id;

	Student(String name, int age, String addr, String school, String major, int id) {
		super(name, age, addr);
		this.school = school;
		this.major = major;
		this.id = id;
	}

	public void showInfo() {
		super.showInfo();
		System.out.println("학교: " + this.school);
		System.out.println("학과: " + this.major);
		System.out.println("학번: " + this.id);
	}

	public void average() {
		Scanner sc = new Scanner(System.in);
		double[] answer = new double[8];
		System.out.println("8학기 학점을 순서대로 입력하세요");

		double sum = 0;
		double average;
		for (int i = 0; i < answer.length; i++) {
			System.out.print((i + 1) + "학기 학점 -> ");

			try {
				answer[i] = sc.nextDouble();
			} catch (InputMismatchException e) {
				e.printStackTrace();
				System.out.println("에러입니다");
				return;
			}

			sum += answer[i];

		}
		average = sum / answer.length;
		System.out.println("8학기 총 평균 평점은" + average + "점 입니다");
	}
}

public class ExceptionMain2 {

	public static void main(String[] args) {
		Student stu = new Student("김다정", 20, "서울시", "동양서울대학교", "전산정보학과", 20132222);
		stu.showInfo();
		stu.average();
	}

}

0개의 댓글