티스토리 뷰

학습정리-11-03.txt
0.00MB

1.Generic 이전의 코드의 문제 상황들을 예시로 설명하시오.

class Apple{
	@Override
	public String toString() {
		return "I am an apple.";
	}
}

class Orange{
	@Override
	public String toString() {
		return "I am an orange.";
	}
}

class Box{ // 무엇이든 담을 수 있는 상자
	private Object ob; // 모든 형을 받아내기 위해서 object 사용
	
	public void set(Object o) {
		// if(o instanceof Apple) 
		// 이렇게 할수도 있지만 일일히 많은 클래스를 이런식으로 확인하는 것은 불가능...
		ob = o;
	}
	
	public Object get() {
		return ob;
	}
}

public class BoxTest {

	public static void main(String[] args) {
		/*
		Box cBox = new Box(); // 상자 생성
		Box eBox = new Box(); // 상자 생성
		
		// 과일을 박스에 담은 것일까? 
        cBox.set("Apple"); 
        eBox.set("Orange");
        // 객체 과일이 아니라 문자열 과일을 담음
        // object가 최상위 부모 클래스라 문자열을 넣어도 컴파일 오류가 나타나지 않는다.
        
        
        // 박스에서 과일을 제대로 꺼낼 수 있을까?
        Apple aa = (Apple)cBox.get(); // Apple은 string인데 형변환 시도.....
        Orange oo = (Orange)eBox.get();
        // 프로그램 실행시 여기서 컴파일 오류가 발생
        
        System.out.println(aa);
        System.out.println(oo);
        // 출력되지 않음. 실무에서 실제로 자주 발생하는 문제.
		*/
		
		
		Box gBox = new Box();
		Box nBox = new Box();
		
		//이 코드는 실행해도 실시간 오류조차 발생하지 않는다!! 더 큰 문제이다.
		// 컴파일러는 value값 오류를 체크하지 못한다.
		gBox.set("Apple");
		nBox.set("orange");
		
		System.out.println(gBox.get()); // Apple 출력
		System.out.println(nBox.get()); // orange 출력
		//I am an ~ 이 출력되지 않는다!!
		
		
		Box aBox = new Box(); // 상자 생성
		Box oBox = new Box(); // 상자 생성

		aBox.set(new Apple()); // 상자에 사과를 담는다.
		oBox.set(new Orange()); // 상자에 오렌지를 담는다.
		
		// 반드시 형 변환해야한다.
		Apple ap = (Apple) aBox.get(); // 상자에서 사과를 꺼낸다.
		Orange og = (Orange) oBox.get(); // 상자에서 오렌지를 꺼낸다.

		System.out.println(ap);
		System.out.println(og);

	}
}

<Generic(제네릭)의 장점>

1. 제네릭을 사용하면 잘못된 타입이 들어올 수 있는 것을 컴파일 단계에서 방지할 수 있다.

2. 클래스 외부에서 타입을 지정해주기 때문에 따로 타입을 체크하고 변환해줄 필요가 없다. 즉, 관리하기가 편하다.

3. 비슷한 기능을 지원하는 경우 코드의 재사용성이 높아진다.

 

출처

 

 

 

 


2. 아래의 결과가 나오도록 프로그래밍 하시오.
class DDBoxDemo {
    public static void main(String[] args) {
        DBox<String, Integer> box1 = new DBox<>();
        box1.set("Apple", 25);

        DBox<String, Integer> box2 = new DBox<>();
        box2.set("Orange", 33);
        
        DDBox<DBox<String, Integer>, DBox<String, Integer>> ddbox = new DDBox<>();
        ddbox.set(box1, box2);

        System.out.println(ddbox);
    }
}

/*
==================
Apple & 25
Orange & 33
*/

class DBox<T1, T2> {
	private T1 ob1;
	private T2 ob2;

	public void set(T1 ob1, T2 ob2) {
		this.ob1 = ob1;
		this.ob2 = ob2;
	}

	@Override
	public String toString() {
		return ob1 + " & " + ob2;
		// ob1.toString() + " & " + ob2.toString()        
	}
}

class DDBox<T1, T2> {
	private T1 ob1;
	private T2 ob2;

	public void set(T1 ob1, T2 ob2) {
		this.ob1 = ob1;
		this.ob2 = ob2;
	}

	@Override
	public String toString() {
		return ob1 + "\n" + ob2;
	}
}

class DDBoxDemo {

	public static void main(String[] args) {
		DBox<String, Integer> box1 = new DBox<>();
		box1.set("Apple", 25);

		DBox<String, Integer> box2 = new DBox<>();
		box2.set("Orange", 33);

		DDBox<DBox<String, Integer>, DBox<String, Integer>> ddbox = new DDBox<>();
		ddbox.set(box1, box2);

		System.out.println(ddbox);

	}
}



 



3.아래와 같이 결과 값이 나오도록 만드시오.
   public static void main(String[] args) {
        DBox<String, Integer> box = new DBox<String, Integer>();
        box.set("Apple", 25);
        System.out.println(box);
        
        DBox<String, String> box2 = new DBox<String,String>();
        box2.set("Apple", "Orange");
        System.out.println(box2);

Apple & 25
Apple & Orange

class DBox7<T1, T2>{
	private T1 ob1;
	private T2 ob2;
	
	public void set(T1 ob1, T2 ob2) {
		this.ob1 = ob1;
		this.ob2 = ob2;
	}
	
	@Override
	public String toString() {
		return ob1 + " & " + ob2;
	}
}


class DBoxTest {

	public static void main(String[] args) {
	      DBox7<String, Integer> box = new DBox7<String, Integer>();
	        box.set("Apple", 25);
	        System.out.println(box);
	        
	        DBox7<String, String> box2 = new DBox7<String,String>();
	        box2.set("Apple", "Orange");
	        System.out.println(box2);
	}
}

 

 

 

 

4. 업다운 게임을 짜시오.

1. 랜덤으로 숫자를 생성 - 컴퓨터가 가짐 (1~100사이 수)
2.게임을 시작 유저가 숫자를 입력
3. 10번의 기회를 주어 맞으면 맞았다고 출력 10번의 기회가 지나면 게임 종료.

출력의 예
========================================

**************
1. 게임 시작
2. 게임 종료
**************
1
게임시작
>>>
50
down
>>>
45
down
>>>
30
down
>>>
20
down
>>>
10
up
>>>
15
up
>>>
17
맞았다
**************
1. 게임 시작
2. 게임 종료
**************

import java.util.Scanner;

class UpDownGameTest {

	public static void main(String[] args) {

		Scanner sc;

		while (true) {

			int start;
			System.out.println("**************");
			System.out.println("1. 게임 시작");
			System.out.println("2. 게임 종료");
			System.out.println("**************");
			try {
				sc = new Scanner(System.in);
				start = sc.nextInt();
				if (start == 1) {
					int comNum = (int) (Math.random() * 100 + 1);
					int num;
					System.out.println("게임시작");

					int count = 0;
					while (count < 10) {
						System.out.println(">>>");
						num = sc.nextInt();

						if (num > comNum) {
							System.out.println("down");
							count++;
							System.out.println((10 - count) + "번 남았습니다.");
						} else if (num < comNum) {
							System.out.println("up");
							count++;
							System.out.println((10 - count) + "번 남았습니다.");
						} else {
							System.out.println("맞았다");
							break;
						}
						
						if(count == 10) {
							System.out.println("아쉽네요. 기회가 끝났습니다.");
						}

					} // while(count)


				} else {
					System.out.println("게임 종료");
					break;
				}
			} catch (Exception e) {
				System.out.println("잘못된 입력입니다. 다시 입력해 주세요.");
				// sc.nextLine();

			}

		} // while(true)

	}
}

sc.nextInt();로 받으면 enter가 계속 입력된 채로 비워지지 않았기 때문에 프로그램이 멈추지 않고 계속 실행되는 요류가 발생한다. sc.nextLine();을 써서 버퍼를 비워주거나 스캐너 객체를 try 문 안에  생성해 주기!

 

import java.util.Scanner;

class UpDownGame {
	private static int COUNT = 10;
	private int[] arrInput;
	private int answer;

	public UpDownGame() {
		arrInput = new int[COUNT];
		answer = (int) (Math.random() * 100 + 1);
	}

	public void run() {
		try {
			Scanner sc = new Scanner(System.in);

			for (int i = 0; i < arrInput.length; i++) {
				System.out.println("숫자를 입력해 주세요.");
				int num = sc.nextInt();

				if (num > answer) {
					System.out.println("Down ===> " + (COUNT - i - 1) + "번 남았습니다.");
				} else if (num < answer) {
					System.out.println("UP ===> " + (COUNT - i - 1) + "번 남았습니다.");
				} else {
					System.out.println("일치");
					break;
				}
			}
			
		} catch (Exception e) {
			System.out.println("잘못된 입력입니다. 처음부터 다시 입력하세요.");
			run(); // 재귀 호출
		}

	}

}

class UpDownGameTest {

	public static void main(String[] args) {
		Scanner sc;
		UpDownGame game;
		
		while(true) {
			try {
				sc = new Scanner(System.in);
				
				System.out.println("게임시작 1");
				System.out.println("게임종료 2");
				System.out.println(">>");
				
				int num = sc.nextInt();
				
				if(num == 1) {
					game = new UpDownGame();
					game.run();
				}else {
					System.out.println("게임을 종료합니다.");
					break;
				}
			} catch (Exception e) {
				System.out.println("잘못된 입력입니다.");
				System.out.println("게임을 다시 시작 합니다.");
			}
			
					
		} // while(true)
		
	}
}

클래스 객체로 빼주는 거 너무 어렵.........연습하기.......

일단 메인에 먼저 만들어보고 그다음에 클래스를 만들고 함수 하나 안에 다 넣어보고 감을 잡는 수밖에 없다....

 


주간 히트송 HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <table border="1">
            <tr>
                <td>
                    <h1>주간 히트 노래</h1>
                    <hr>
                    <ol>
                        <li><img src="img01.png" alt="">
                            <a href="#">어머니 누구니</a>
                        </li>

                        <li><img src="img02.png" alt="">
                            <a href="#">한번 더 말해줘</a>
                        </li>

                        <li><img src="img03.png" alt="">
                            <a href="#">다른 남자 말고 너</a>
                        </li>

                        <li><img src="img04.png" alt="">
                            <a href="#">모두가 내 발아래</a>
                        </li>

                        <li><img src="img05.png" alt="">
                            <a href="#">조만간 봐요</a>
                        </li>                       
                    </ol>
                    <p><audio src="34ex1.mp3" controls="controls" autoplay = "autoplay" loop = "loop"></audio></p>
                </td>
            </tr>    
        </table>
    </body>
</html>

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함