본문 바로가기
Backend

06월 04일 화 | OOP 14 - JAVA의 상속과 다형성, Object과 Exception

by 구라미 2019. 6. 4.

10. 객체지향 프로그래밍 Ⅱ

Super

상속관계에서 부모, 조상의 개념을 Super라고 한다.

 

super : 자식클래스에서 부모클래스 멤버변수에 접근할 때

super() : ()가 붙으면 함수, 함수로 호출 자식클래스의 생성자함수가 부모클래스의 생성자함수를 호출할 때.

 

this : 멤버변수(field)와 지역변수 구분하기 위해서.

this() : ()가 붙으면 함수, 자신의 생성자 함수를 호출할 때.

부모클래스 : superclass

자식클래스 : subclass

 

상속관계에서 생성자함수 호출순서

부모 -> 자신

//School() -> MiddleSchool()

 

부모생성자함수를 호출하는 명령어

super(); //생략가능하다.

 

복사가 되어도 부모에게 접근가능하다.

내 것을 정의하기 전 -> 부모의 것만

내 것을 정의한 후  -> 내 것과 부모의 것 모두

 

상속 예제 1)

package oop0604;

//부모클래스
class School {
	String name = "학교";
	public School(){
		System.out.println("School()...");
	}
}

//자식클래스 1
class MiddleSchool extends School {
	String name = "중학교"; //지역정보가 우선순위가 높다.
	public MiddleSchool(){
		System.out.println("MiddleSchool()...");
	}
}

//자식클래스 2
class HighSchool extends School {
	//부모 School
	//자식 HighSchool
	String name = "고등학교";
	public HighSchool() {
		super();// 생략가능
	}
	public void disp(){ //method 멤버함수
		String name ="종로고등학교"; //지역번수 이 범위 밖을 나가면 영향력을 잃는 개념.
		System.out.println(name);//지역변수
		System.out.println(this.name);//내 변수
		System.out.println(super.name);//부모 변수
		
	}	
}

public class Test01_Super {
	public static void main(String[] args) {

		School sch = new School();
		MiddleSchool ms = new MiddleSchool();
		System.out.println(ms.name); //중학교
		
		HighSchool hs = new HighSchool();
		System.out.println(hs.name); //학교		
		
	}//main end
}//class end

 

상속 예제 2)

package oop0604;

class Parent {
	int one;
	int two;
	
	public Parent(){}
	public Parent(int one, int two){
		this.one = one;
		this.two = two;		
	}	
}

class Child extends Parent {
	int three;

	public Child() {
		//super(); 생략되어 있음.
	}

	public Child(int a, int b, int c) {
		super(a,b);
		//super.one = a;
		//super.two = b;
		//와 같은 표현이다.
		three = c;
	}
}

public class Test02_Super {
	public static void main(String[] args) {
		//부모클래스 super
		Child child = new Child(10,20,30);
		System.out.println(child.one);
		System.out.println(child.two);
		System.out.println(child.three);
		
	}//main end
}//class end

 

객체

 

다형성

상속관계에서의 다형성. 형태가 여러가지라는 뜻이다. 다형성이 없으면 변환작업 어려움.

부모클래스 입장에서 형태가 여러가지.

다형성이란 하나의 객체가 여러가지 타입을 가질 수 있는 것을 의미한다.

자바에서는 이러한 다형성을 부모클래스타입의 참조 변수로 자식클래스타입의 인스턴스를 참조할 수 있도록

하여 구현하고 있다.

 

다형성은 상속, 추상화와 함께 객체지향 프로그래밍을 구성하는 중요한 특징 중 하나이다.

 

1. 다형성은 하나의 객체를 여러 타입으로 선언할 수 있다는 뜻이다.

2. Java에서 다형성은 상속과 인터페이스를 통해 이루어진다.

3. 인터페이스가 상속보다 다형성에 더욱 유연함을 제공한다.

 

클래스들간의 형변환을 위해서,

1) 일반적인 방식의 객체 생성

new 연산자를 사용하는 방식이다.

POJO(Plain Old Java Object) 방식이라고 한다.

 

package oop0604;

class Father extends Object {
	public String name = "아버지";
	public String addr = "주소";
	
	public Father() {}
	public Father(String name, String addr) {
		this.name = name;
		this.addr = addr;
	}
	
	public void disp () {
		System.out.println(this.name);
		System.out.println(this.addr);
	}
}//Father end

class Son extends Father {
	public Son(){}
	public Son(String n, String a){
		super.name = n; //개별접근
		super.addr = a;
	}
}//class end

class Daughter extends Father {

	public Daughter() {}
	public Daughter(String name, String addr) {
		super(name, addr); //생성자형태 Son클래스의 개별접근과 의미는 같다.
	}	
}//class end



public class Test03_Polymorphism {
	public static void main(String[] args) {
		//polymorphism 다형
		//상속관계에서의 다형성
		//부모클래스 입장에서 형태가 여러가지
		Father fa = new Father();
		fa.disp();
		
		Son son = new Son("손흥민","영국");
		son.disp();
		
		Daughter daut = new Daughter("김연아","캐나다");
		daut.disp();
		
//-------------------------------------------------------------
		
	}//main end
}//class end

Father라는 부모클래스 안에 Son, Daughter라는 자식클래스를 생성하였다.

그리고 새로 값을 넣어주었다.

새로 값을 넣어주지 않으면 부모의 값이 출력된다.

 

2) 상속관계에서 다형성을 이용한 객체를 생성

자식클래스가 부모클래스에 대입 가능하다.

부모클래스는 자식클래스의 모양으로 형태를 변경한다.

Father fa = new Son("개나리","관철동"); //가능하다. 자식이 부모집에 들어갈 수 있듯
fa.disp(); //원활히 출력된다.
		
fa = new Daughter("진달래","인사동");
fa.disp(); //원활히 출력된다.

결과값:

개나리
관철동
진달래
인사동

 

Son이 들어오면 Son의 모습으로, Daughter가 들어오면 Daughter의 모습으로 변함.

다 되는 것은 아니고 제약조건이 있음. 부모가 물려준 것에 한해서 변경.

다형성은 인터페이스에서 많이 사용한다.

//부모클래스도 자식클래스에 대입가능하다.
//(단,자식의 모양으로 형변환을 해야함)
//부모도 자식 집에 들어갈 수 있다, 하지만 자주는 안쓰임.
Father father = new Father();
Son son = new Son();
Daughter daut = new Daughter();
		
father = son; //자식이 부모에 대입.
son = (Son)father; //부모가 자식에 대입.
daut = (Daughter)father; //부모가 자식에 대입.

에러는 아닌데 exception이 나올 수 있다. 문제가 많아서 잘 안쓴다고 함.

 

선생님 권장교재

이것이 자바다, 신용권

 

 

Object

자바 클래스의 최고 조상: Object

자바의 모든 클래스는 Object클래스의 후손이다.

자바의 모든 클래스는 Object클래스에 대입가능하다.(다형성)

//Object클래스와 다형성
Integer inte = new Integer(3);
Object inte1 = new Integer(3); //부모인 Object도 가능하다.
Object fa = new Father(); //가능하므로 에러가 아니다.

Object와 다형성

//다형성
//객체생성 시 이런 식으로도 가능하다. Object클래스가 모든 클래스의 최고 조상이라서
Object obj = new Integer(5);
System.out.println(obj);
		
obj = new String("soldesk");
System.out.println(obj);
		
obj = new Double(3.4);
System.out.println(obj);
		
//Double dou = obj; //에러. 조상이 후손에 들어가려면 형변환해야한다.
Double dou1 = (Double) obj; //형변환을 해주었더니
System.out.println(obj); //성공적으로 출력된다.

메소드의 매개변수가 Object일 경우를 잘 봐야한다.

 

메소드와 관련된 Object클래스

1) 매개변수가 Object클래스

class Print {
	//static : 클래스명. 멤버변수
	//		   클래스명. 멤버함수()
	
	//Overloading, 오버로딩 매개변수 다른 이름같은 함수들.
	//매개변수의 자료형과 갯수로 구분.
	public static void view(Integer a){
		System.out.println(a.toString());
	}
	public static void view(Double a){
		System.out.println(a.toString());
	}
	public static void view(String a){
		System.out.println(a.toString());
	}	
	public static void view(Object obj){
		System.out.println(obj.toString());
	}
	
	
}//class end

 

//1) 매개변수가 Object클래스
//아래 세 클래스는 Object 클래스로 들어올 수 있다.
Print.view(new Integer(3));
Print.view(new Double(5.6));
Print.view(new String("Happy"));
Print.view(new Father()); //제대로 메모리 할당을 하였다.고 출력됨.
		
//autoboxing
//기본형값이 전달되면
//참조형으로 자동으로 변환된다.
Print.view(7);
Print.view(new Double(5.6));

 

2) 메소드의 리턴형이 Object클래스

	public static void view(Integer a){
		System.out.println(a.toString());
	}
	public static void view(Double a){
		System.out.println(a.toString());
	}
	public static void view(String a){
		System.out.println(a.toString());
	}	
	public static void view(Object obj){
		System.out.println(obj.toString());
	}
	
	public static Integer disp1(){
		return new Integer(3);
	}
	
	public static Double disp2(){
		return (5.6); //알아서 Double로 넘김, autoboxing
	}
	
	public static Object disp3(){
		return new Integer(9);
	}
	
	public static Object disp4(){
		return new Double(3.4);
	}
	
	public static Object disp5(){
		return "happy";		
	}


//----------------------------------------------------------


//2) 메소드의 리턴형이 Object 클래스
		Integer a = Print.disp1();
		System.out.println(a);
		
		Double b = Print.disp2();
		System.out.println(b);
		
		Object obj = Print.disp3();
		System.out.println(obj.toString());
		
		Double c = (Double) Print.disp4();
		System.out.println();
		
		String d = (String) Print.disp5();
		System.out.println(d);

 

다형성과 메소드

package oop0604;

class Screen {
	public String getData(){
		return "-";
	}
}//class end

class TypeA extends Screen{
	@Override
	public String getData() {
		return "기생충";
	}	
} //class end


class TypeB extends Screen{
	@Override
	public String getData() {
		return "어벤져스";
	}
	
} //class end

class TypeC extends Screen{
	@Override
	public String getData() {
		return "악인전";
	}
} //class end

class Picture {
	public static void dispStar (TypeA ta){
		System.out.println(ta.getData());	
	}
	public static void dispStar(TypeB tb){
		System.out.println(tb.getData());
	}
	//2) 다형성
	public static void dispStar(Screen scr){
		System.out.println(scr.getData());
	}
	
	//3) 다형성
	public static void dispStar(Object obj){
		Screen scr = (Screen) obj;
		System.out.println(scr.getData());
	}
	
	
}







public class Test05_Object {

	public static void main(String[] args) {
		
		//Object 클래스 : 자바의 최상위 클래스
		
		//1) 다형성
		Screen scr1 = new TypeA();
		System.out.println(scr1.getData());
		
		scr1 = new TypeB();
		System.out.println(scr1.getData());
		
		
		//--------------------------------------------------------
		
		TypeA ta = new TypeA();
		TypeB tb = new TypeB();
		Screen scr = new Screen();
		
		Picture.dispStar(ta);
		Picture.dispStar(tb);
		Picture.dispStar(scr);
		
	}//main end
}//class end

꼭 레퍼런스 찾아서 분석해보기

 


Exception

자바의 예외처리.

에러이다. 그러나 코딩상의 에러가 아니다. (오타, 누락 등이 아닌)

자바 클래스 실행 시 발생하는 에러
1) try~catch 문
2) throws문
3) finally문

으로 해결한다.

 

1)Exception을 처리하지 않은 경우

package oop0604;

public class Test06_Exception {

	public static void main(String[] args) {
		// Exception 예외처리
		//자바 클래스 실행 시 발생하는 에러
		//try~catch 문
		//throws문
		//finally문
		
		//1)Exception을 처리하지 않은 경우
		System.out.println(1);
		System.out.println(2/0); //ArithmeticException 발생하였다.
		System.out.println("END");
		
	}//main end
}//class end

다음과 같은 현상이 나타난다.

 

2)Exception 처리한 경우

코딩하다가 예외가 발생할 것 같은 코드들을 try~catch문 안에 가둔다.

//2)Exception 처리한 경우
try { 
  //예외가 발생될 예상이 되는 코드를 작성
  System.out.println(1); //정상실행
  System.out.println(2/0); //Exception 발생
  System.out.println(3); //이 후 명령어 무시.
  } catch(ArithmeticException e){
	//예외가 발생되면 처리할 코드를 작성
	//사실상 프로그래머가 직접 고쳐야함.
    
}//try end
System.out.println("end");

//결과값
//1
//end

 Exception이 발생되는 부분이 있을 경우는 그 후 명령어는 무시되고 바로 catch로 넘어간다.

 

3) 배열에 Exception 발생했을 때

//3)Exception 처리한 경우
		
		try {
			System.out.println(1);
			int[] su = new int[3];
			su[3] = 5;
			System.out.println(2);
		
		} catch(ArrayIndexOutOfBoundsException e){ //원인을 알려주는 것.
			
		}	System.out.println("END");

 

경우는 

4) NumberFormatException 발생했을 때 Numberformat 안맞을때

//4)Exception 처리한 경우
		
		try{
			System.out.println(1);
			int su = Integer.parseInt("Soldesk");
			System.out.println(2);
			
		}catch(NumberFormatException e){
			System.out.println(e);
		}
		System.out.println("END");
		
		

 

 

5) NullPointerException Null값

//5)Exception 처리한 경우

try {
	System.out.println(1);
	int su = Integer.parseInt(null);
	System.out.println(2);
}catch(NullPointerException e){
	System.out.println(e);
}
System.out.println("end");

 

6) 다중 catch문

catch문도 다중으로 사용할 수 있다.

//6)다중 catch문, catch문도 여러 개 나올 수 있다.
try{
  int a = Integer.parseInt("Happy");
  int b =3/0;
  int[] su =new int[3];
  su[3]=5;			
}catch(ArrayIndexOutOfBoundsException e){
	System.out.println(e);
}catch(NumberFormatException e){
	System.out.println(e);
}catch(NullPointerException e){
	System.out.println(e);
}
//이렇게 할 수 있지만 너무 많은걸 한꺼번에 쓸 수 없음..

흔하게 볼 수 있는 메세지들이니 유의해서 볼 것.

subclasses //자식들

 

 

Exception 종류가 많다.

하지만 자주 접하는 것의 종류는 10개 내외

 

 

7) 다형성을 이용한 예외처리

//7) 다형성을 이용한 예외처리
		
try{
  int a=Integer.parseInt("happy");
  int b = 3/0;
  int[] su=new int[3];
  su[3]=5;
} catch(Exception e){
//Exception 클래스
//모든 Exception의 조상
//다형성
	
	System.out.println(e);
}
System.out.println("end");

 

8) finally문
-> 예외가 발생하거나 발생하지 않거나.
-> finally문은 무조건 실행

//8) fninally문
//-> 예외가 발생하거나 발생하지 않거나.
//-> 무조건 실행
		
try{
	System.out.println(1);
	System.out.println(2/0);
	System.out.println(1);
}catch(Exception e) {
	System.out.println(e);
}finally {
	System.out.println("close"); //무조건 실행하고 프로그램 종료
}

 

 

9) throw문

메소드 호출 시 예외처리를 한꺼번에 모아서 처리.

package oop0604;

class Test {
/*	//1) try~catch를 이용한 예외처리
	public void view(){
		try{
			int a = 3/0;
		}catch(Exception e){}
	}//class end
	
	public void disp(){
		try{
			int a = Integer.parseInt("soldesk");
		}catch(Exception e){}
	}//class end
*/	
	
	//2)throws를 이용한 예외처리
	public void view() throws Exception { //예외가 생기면 catch로 던지기
		int a = 3/0;
	}
	public void disp() throws NumberFormatException {
		int a = Integer.parseInt("soldesk");
	}
	
}//class end


public class Test07_Exception {
	public static void main(String[] args) {
		//throws문
		//->메소드 호출 시 예외처리를 한꺼번에 모아서 처리.
		
		try {
			Test test = new Test();
			test.view();
			test.disp();
			
		}catch (Exception e){ //아까 던진 throws문을 여기서 받는다.
			System.out.println(e);
		}
		
		
		
	}//main() end
}//class end

 


getter, setter

getter와 setter 메소드이다. 

객체지향 프로그래밍에서 객체의 데이터는 객체외부에서 직접적으로 접근하는 것을 막기 때문에

외부에서 마음대로 읽고 변경할 경우 객체의 무결성이 깨질 수 있어 메소드를 통해 데이터를 변경하는 방법을

선호한다.

private으로 선언된 인스턴스 필드에 접근하기 위해 getter와 setter를 사용한다.

getter는 Main 메소드에서 인스턴스필드에 접근해 사용하는 메소드이다. 초기화된 멤버변수를 리턴한다.

setter는 Main 메소드에서 인스턴스필드에 접근해 사용하는 메소드이다. 매개변수로 멤버변수를 초기화한다.

 

getter메소드

- 반드시 소문자 get을 접두사로 사용

- get다음은 camelcase로 작성

- 반드시 리턴값이 있어야한다. (void 불가)

- 매개변수가 없어야한다.

 

setter메소드

- 반드시 소문자 set을 접두사로 사용

- set 다음은 camelcase로 작성

- 반드시 리턴값이 없어야한다.(void형이어야만 한다)

- 반드시 매개변수가 있어야한다.

 

 

1) 가장 일반적인 사례

package oop0604;

class Member {
	
	private String id;
	private String passwd;
	
	public void setId(String id){
		this.id = id; //필드를 private으로 막아놔도 메소드를 매개로 접근할 수 있음.
	}
	
	public String getId(){
		return this.id;
	}
	
	public void setPasswd(String passwd){
		this.passwd = passwd;
	}
	
	public String getPasswd(){
		return this.passwd;
	}
	

}//class end

public class Test08_GetSet {

	public static void main(String[] args) {
		// getter, setter 함수
		
		Member mem = new Member();
		mem.setId("soldesk");
		mem.setPasswd("1234");
		
		System.out.println(mem.getId());
		System.out.println(mem.getPasswd());

	}

}

 

Getters, Setters 세트로 불러오기

 

 


 

 

과제 1) 성적프로그램 OX 표시하기

          ** 시험결과 **
=========================
번호 이름    1  2  3  4  5  점수 등수      
------------------------------------    
1    홍길동  ○ X  ○ ○ ○  80  2    
2    무궁화  ○ ○ ○ ○ ○ 100  1
3    라일락  X  X  X  X  ○  20   5
4    진달래  X  ○ X  ○ ○  60   3
5    봉선화  ○ ○ X  X  X   40   4
------------------------------------   

- 맞힌문제 ○ , 틀린문제 X표시
- 점수: ○당 20점씩
- 등수: 점수를 기준으로 높은사람이 1등
- 정렬: 등수를 기준으로 오름차순 정렬

 

package oop0604;

class Sungjuk{
	private int no;						//번호
	private String name;				//이름
	private int[] answer = new int[5];	//답안제출
	private char[] ox = new char[5];	//OX표시
	public int score;					//점수
	public int rank;					//등수
	
	//공통의 한 사람 것만 설계해서 만들고 나머지 배열.
	public Sungjuk(){}
	public Sungjuk(int no, String name, int a, int b, int c, int d, int e){
		this.no=no;
		this.name=name;
		this.answer[0]=a;
		this.answer[1]=b;
		this.answer[2]=c;
		this.answer[3]=d;
		this.answer[4]=e;
		this.rank=1;
	
	}

	public void compute(){
		//제출한 answer답안과 정답을 비교해서 
		//OX를 구하고, 맞은 갯수에 따라 점수를 구하기
		int[] dap = {1,1,1,1,1}; //정답
		
	}//compute end
	
	public void disp(){
		//출력하기
	}//disp end
	
	
}//class end

public class Test09_OX {

	public static void main(String[] args) {
		// 성적프로그램
		// pretyimo.cafe24.com
		// -> OOP
		// -> 글번호 [25] [예제] 성적프로그램 OX 표시 하기
		
		Sungjuk[] student = {
				new Sungjuk(1, "김다현", 1,2,1,1,1),
				new Sungjuk(2, "유정연", 1,1,1,1,1),
				new Sungjuk(3, "손채영", 3,2,4,2,1),
				new Sungjuk(4, "임나연", 2,1,4,1,1),
				new Sungjuk(5, "박지효", 1,1,4,3,2)
				
		};
		
		int size = student.length;
			
		
	}//main end
}//class end

 

내 풀이

package oop0604;

class Sungjuk{
	private int no;								//번호
	private String name;						//이름
	private int[] answer = new int[5];			//답안제출
	private char[] ox = new char[5];			//OX표시
	public int score;							//점수
	public int rank;							//등수
	
	//공통의 한 사람 것만 설계해서 만들고 나머지 배열.
	public Sungjuk(){}
	public Sungjuk(int no, String name, int a, int b, int c, int d, int e){
		this.no=no;
		this.name=name;
		this.answer[0]=a;
		this.answer[1]=b;
		this.answer[2]=c;
		this.answer[3]=d;
		this.answer[4]=e;
		this.rank=1;
	
	}

	public void compute(){
		//제출한 answer답안과 정답을 비교해서 
		//OX를 구하고, 맞은 갯수에 따라 점수를 구하기
		int[] dap = {1,1,1,1,1}; //정답
		//int sRank[] =new int[5];
			
		//1) 답과 제출한 것을 OX판별하고 점수계산
		for(int idx = 0; idx<dap.length; idx++){
			if(this.answer[idx]==dap[idx]){				
				ox[idx] = 'O';
				score = score + 20;
			}else{
				ox[idx] = 'X';
			}
		}//for end
		
		/*for(int i = 0; i<ox.length; i++){
			System.out.print(ox[i]);
		}*/
		
	/*	for(int i = 0; i<sRank.length; i++){
			sRank[i] = this.score;
			if(sRank[0]<sRank[i]){
				rank = rank+1;
			}
		}*/
				
	}//compute end
	
	public void disp(){
		//출력하기
		System.out.print(no+" ");
		System.out.print(name+" ");
		System.out.print(ox[0]);
		System.out.print(ox[1]);
		System.out.print(ox[2]);
		System.out.print(ox[3]);
		System.out.print(ox[4]+" ");
		System.out.print(score+" ");
		System.out.print(this.rank);
		System.out.println();

		
	}//disp end
	
	
}//class end

public class Test09_OX {

	public static void main(String[] args) {
		// 성적프로그램
		// pretyimo.cafe24.com
		// -> OOP
		// -> 글번호 [25] [예제] 성적프로그램 OX 표시 하기
		
		Sungjuk[] student = {
				new Sungjuk(1, "김다현", 1,2,1,1,1),
				new Sungjuk(2, "유정연", 1,1,1,1,1),
				new Sungjuk(3, "손채영", 3,2,4,2,1),
				new Sungjuk(4, "임나연", 2,1,4,1,1),
				new Sungjuk(5, "박지효", 1,1,4,3,2)
				
		};
		
		int size = student.length;
		
		for(int idx=0; idx<size; idx++){			
						
			student[idx].compute();		
			//student[idx].disp(); //점수계산 -> 순서가 매우 중요하다.			
		}
		
		
		
		//1) 점수내기
		//answer 배열과 dap 배열 비교하기
		//불러와서 비교	
		//0에서 증가형식으로 갈지.
		//if 만약 answer[i] dap[i]이 일치하지 않으면 -20

		
		//2) 등수내기
		//위의 절차 후 담은 변수들의 값 끼리 비교해서 등수 카운트하기.
		//score에 담긴 값들을 비교
		//배열로 비교해서 카운트 ->이 부분에서 막혔음.
		for(int a=0; a<size; a++){
			for(int b=0; b<size; b++){
				if(student[a].score < student[b].score){ //student배열이 있으니까 그거 이용하기.
					student[a].rank = student[a].rank+1;
				}
			}
		}
		
		
		
		
		
		//3) 정렬하기
		//출력 -> 시작도 못했음..위에서 막힌 개념을 이해한다면 할 수 있을 것 같다.
		
		
		//4) 출력하기
		
		for(int idx=0; idx<size; idx++){			
	
			student[idx].disp(); //점수계산 -> 순서가 매우 중요하다.			
		}
		
		
			
		
	}//main end
}//class end

▶ 풀이

나는 답 판별해서 OX출력하고 점수를 매긴것은 성공했지만 그 이후의 과정과 출력은 하지 못했다.

Sungjuk 클래스와 Sungjuk메소드(매개변수: int no, String name, int a, int b, int c, int d, int e) 

그리고 main메소드의 Sungjuk[] 배열의 student[숫자]요소의 값이 유기적으로 어떤관계를 갖는지 어떻게 연결되는지

이해하지 못했기 때문에 풀기가 어려웠다.

 

 

선생님 풀이

package oop0605;

import oop0605.Sungjuk;

class Sungjuk{
  private int no;					//번호
  private String name;				//이름
  private int[] answer = new int[5];//답안제출
  private char[] ox = new char[5];	//OX표시
  public int score;					//점수
  public int rank;					//등수
	
//공통의 한 사람 것만 설계해서 만들고 나머지 배열.
  public Sungjuk(){}//생성자메소드로 초기화
  public Sungjuk(int no, String name, int a, int b, int c, int d, int e){
	this.no=no;
	this.name=name;
	this.answer[0]=a;
	this.answer[1]=b;
	this.answer[2]=c;
	this.answer[3]=d;
	this.answer[4]=e;
	this.rank=1;
  }//Sungjuk end

//계산하기
public void compute(){
//제출한 answer답안과 정답을 비교해서 
//OX를 구하고, 맞은 갯수에 따라 점수를 구하기
  int[] dap = {1,1,1,1,1}; //정답
		
  //1) 답과 제출한 것을 OX판별하고 점수계산
  for(int idx=0; idx<dap.length; idx++){
    if(this.answer[idx]==dap[idx]){
		ox[idx]='O';
	score = score+20;//한 문제당 20점씩
	}else{
		ox[idx]='x';
	}
  }//for end		
}//compute end

//출력하기
public void disp(){
  System.out.println();
  System.out.print(no+" ");
  System.out.print(name+" ");
  System.out.print(ox[0]+" ");
  System.out.print(ox[1]+" ");
  System.out.print(ox[2]+" ");
  System.out.print(ox[3]+" ");
  System.out.print(ox[4]+" ");
  System.out.print(score+" ");
  System.out.print(this.rank+" ");
  System.out.println();
  System.out.println("-----------------");		
 }//disp end
}//class end

public class Test09_OX_A {
  public static void main(String[] args) {
  // 성적프로그램
  // pretyimo.cafe24.com
  // -> OOP
  // -> 글번호 [25] [예제] 성적프로그램 OX 표시 하기
  Sungjuk[] student = {
	new Sungjuk(1, "김다현", 1,2,1,1,1),
	new Sungjuk(2, "유정연", 1,1,1,1,1),
	new Sungjuk(3, "손채영", 3,2,4,2,1),
	new Sungjuk(4, "임나연", 2,1,4,1,1),
	new Sungjuk(5, "박지효", 1,1,4,3,2)	
};	
  int size = student.length;
  //1) 점수계산하기  
  for(int idx=0; idx<size; idx++){
    student[idx].compute();
  }	
		
  //2) 등수구하기 5명 모두 구해야하니까 사각형 반복문
  for(int a=0; a<size; a++){
 	for(int b=0; b<size; b++){
		if(student[a].score < student[b].score){
			student[a].rank = student[a].rank+1;
		}//if end
  	 }//for end
  }//for end
			
  //3) 정렬하기 (등수를 기준으로 오름차순 정렬)
  Sungjuk tmp; //tmp의 자료형을 모든 정보를 담은 Sungjuk으로 해줘야한다.		
  for(int a =0; a<size-1; a++){ 
    for(int b=a+1; b<size; b++){ //자기자신과 비교할 필요가 없기 때문에 a+1 부터.
     if(student[a].rank>student[b].rank){ //등수의 크기 비교해서 
       tmp = student[b]; //tmp변수에 작은 값을 넣기
       student[b] = student[a]; //작은 값 있던 위치에 큰 값을 넣기
       student[a] = tmp; //큰 값 있던 위치에 작은 값을 넣기				
     }//if end
   }//for end
}//for end
		
  for(int a = 0; a<size; a++){
		student[a].disp();
}//for end
		
  //4) 출력하기
  for(int idx=0; idx<size; idx++){			
	student[idx].disp();
  }//for end
		
	}//main end
}//class end

▶ 풀이

1. class Sungjuk

- private 번호

- private 이름

- private 답안

- private OX판별

- public 점수

- public 등수

를 선언

 

- 생성자 메소드로 초기화

Sungjuk메소드: int no, String name, int a, int b, int c, int d, int e를 매개변수로 받는 에

  위에 선언한 정보를 가져오는 this객체 선언.

- compute 메소드 : 정답배열, this.answer의 정수를 가져와서 정답배열요소와 비교하며 OX판별.

여기서 OX개수에 따라 score계산됨.

- disp 메소드 : 출력

 

2. main 메소드

- Sungjuk의 자료형을 갖는 배열 student안의 new Sungjuk요소들(Sungjuk메소드의 매개변수안에 넣어줄 값이 있다.)

student[0] : (1, "김다현", 1,2,1,1,1),
student[1] : (2, "유정연", 1,1,1,1,1),
student[2] : (3, "손채영", 3,2,4,2,1),
student[3] : (4, "임나연", 2,1,4,1,1),
student[4] : (5, "박지효", 1,1,4,3,2)

인 것임.

- 반복문으로 Sungjuk student[숫자].compute(); : compute메소드를 실행하여 점수내기

- 반목문으로 Sungjuk student[숫자].score를 비교해서 .rank를 매김.

- 등수대로 정렬하기

- 순서대로 Sungjuk student[숫자].disp();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

댓글