Java

[Java] 객체 지향 클래스 ( 캡슐화 / 생성자 오버로딩 / 멤버변수 / this(); / 접근 지정자, 접근 한정자, 접근 수정자 / getter, setter / check )

소댓 2023. 3. 14. 18:49

* 접근지정자, 접근한정자, 접근수정자
- public : 모두에게 허용 된다.
- protected : 동일한 패키지와 상속된 관계 있는 객체만 접근 가능
- default : 동일한 패키지 내에서만 접근 가능
- private : 내 클래스에서만 접근 가능


* 캡슐화(encapsulation)
- 객체의 내부 구조 및 데이터를 캡슐처럼 감싸 외부에서 직접 볼 수 없게 은닉하여 보호하는 것
> 정보의 은닉

 

* getter / setter

- getter
public 자료형 get변수명(){
    return this.변수명;
    }

 

- setter
public void set변수명(자료형 변수명) {
   this.변수 = 변수;
  } 

 


 

 

 

* Human > 생성자의 오버로딩

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package day09;
 
public class Human {
 
    String 이름;
    String 직업;
    String 성별;
    String 전화번호;
    int 나이;
    
    Human() {
        이름 = "무명";
        직업 = "백수";
        성별 = "무";
        전화번호 = "010-111-2222";
        나이 = 20;
        System.out.println("human 기본생성자 호출");    
    }
    
    Human(String a, int b, String c) {
        이름 = a;
        나이 = b;
        성별 = c;
        직업 = "백수";
        전화번호 = "없음";
        System.out.println("String int String 생성자 호출");
    }
    
    Human(String 이름, int 나이, String 성별, String 직업) {
//        int a = 100;
//        a = a; // 의미 없는 코드
        
        // 여기서 이름 이라는 변수는 지역변수? 멤버변수?
        // 멤버변수 = 지역변수;
        this.이름 = 이름; // this.이름 --> 이름이라는 멤버변수
        this.나이 = 나이;
        this.성별 = 성별;
        this.직업 = 직업;
        전화번호 = "없음";
    }
    
    
    Human(String 성별, String 이름, int 나이) {
        this.이름 = 이름;
        this.나이 = 나이;
        this.성별 = 성별;
        직업 = "유아";
        this.전화번호 = "없음";
        System.out.println("String String int 생성자 호출");
    }
    
    // 생성자의 오버로딩
    Human(String a, int b, String c, String d, String e) {
        이름 = a;
        직업 = e;
        성별 = c;
        전화번호 = d;
        나이 = b;
        System.out.println("String int String String String 생성자 호출");
    }
    
    Human(String 이름, String 직업, int 나이, String 성별) {
        this();
        this.이름 = 이름;
        this.직업 = 직업;
        this.나이 = 나이;
        this.성별 = 성별;
    }
    
    void 먹기() {
        System.out.println("맛난 걸 먹어요");
    }
    void 말하기() {
        System.out.println("쏙닥쏙닥");
    }
    void 상태보기() {
        System.out.println("이름 : "+ 이름);
        System.out.println("직업 : "+ 직업);
        System.out.println("성별 : "+ 성별);
        System.out.println("전화번호 : "+ 전화번호);
        System.out.println("나이 : "+ 나이);
    }
        
}
cs

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package day09;
 
public class TestMain {
    
    public static void main(String[] args) {
        
        Human h1 = new Human();
        
        h1.먹기();
        h1.말하기();
        h1.상태보기();
        System.out.println();
        System.out.println("--------------------------");
        // h2
        
        // 이름 : 홍길동
        // 직업 : 도적
        // 성별 : 남
        // 전화번호 : 없음
        // 나이 : 20
        
        Human h2 = new Human("홍길동"20"남""없음""도적");
        
//        h2.이름 = "홍길동";
//        h2.나이 = 20;
//        h2.성별 = "남";
//        h2.전화번호 = "없음";
//        h2.직업 = "도적";
        
        h2.상태보기();
        
        System.out.println();
        System.out.println("--------------------------");
        
        Human h3 = new Human("홍길순"20"여"); // String int String 생성자 호출
        h3.상태보기();
        // 이름 : 홍길순
        // 직업 : 백수
        // 성별 : 여
        // 전화번호 : 없음
        // 나이 : 20
        
        System.out.println();
        System.out.println("--------------------------");
        
        Human h4 = new Human("짱구"5"남""유치원생");
        h4.상태보기();
        // 이름 : 짱구
        // 직업 : 유치원생
        // 성별 : 남
        // 전화번호 : 없음
        // 나이 : 5
        
        System.out.println();
        System.out.println("--------------------------");
        
        Human h5 = new Human("여""짱아"3);
        h5.상태보기();
    }
}
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package day09;
 
public class TestMain03 {
 
    public static void main(String[] args) {
        
        Human h = new Human();
        
        h.상태보기();
        
        
        System.out.println("---------------------");
        System.out.println();
        
        Human iu = new Human("IU""가수"30"여");
        
        iu.상태보기();
        
 
    }
 
}
cs

 

 

 

 

 

*  Marine > this();

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package day09;
 
public class Marine {
    // 클래스의 전역변수
    int hp, x, y, 사거리, 공격력, 방어력;
    int 공격속도, 이동속도;
    
    
    Marine() { 
        hp = 100;
        x = 0;
        y = 0;
        사거리 = 4;
        공격력 = 5;
        방어력 = 3;
        공격속도 = 3;
        이동속도 = 4;
        System.out.println("마린 기본생성자 호출");
        // return XXX
    }
    
    Marine(int hp, int x, int y) { // 체력 500짜리 마린
        // 기본 생성자를 실행하고와
        this(); // 항상 가장 첫번째 라인에 등장해야 한다.
        this.hp = hp;
        this.x = x;
        this.y = y;
        System.out.println("hp x y 생성자 호출");
    }
    
    Marine(int hp, int 공격력, int 공격속도, int 이동속도) {
        // 기본생성자를 호출한 후에 다른값을 대입
        this();
        this.hp = hp;
        this.공격력 = 공격력;
        this.공격속도 = 공격속도;
        this.이동속도 = 이동속도;
        System.out.println("hp 공격력 공격속도 이동속도 생성자 호출");
    }
    
    Marine(int hp, int x, int y, int 공격력, int 이동속도) {
        this(hp, x, y); // 생성자 중 int, int, int 매갭ㄴ수 생성자를 호출
//        this.hp = hp;
//        this.x = x;
//        this.y = y;
        this.공격력 = 공격력;
        this.이동속도 = 이동속도;
        System.out.println("hp x y 공격력 이동속도 생성자 호출");
    }
    
    void 공격하기() {
        System.out.println("뚜뚜뚜뚜뚜");
    }
    
    void 공격하기(Marine x) {
        System.out.println("공격하기 메서드 내부 x : "+x);
        x.hp -= 공격력;
        System.out.println("적 캐릭터 공격!!!");
    }
    
    void 이동하기() {
        System.out.println("GOGOGO~~~");
    }
    
    void 정지() {
        System.out.println("정지");
    }
    
    void 스팀팩() {
        System.out.println();
        if(hp >3 ) {
        System.out.println("오우예~~~");
        hp -= 3;
        공격속도 += 2;
        이동속도 += 2;
    } else {
        System.out.println("체력이 부족합니다.");
    }
    }
    
    void 패트롤() {
        System.out.println("순찰중~~~");
    }
    
    void status() {
        System.out.println("---------------------");
        System.out.println("체력 : "+hp);
        System.out.println("x : "+x+" , y : "+y);
        System.out.println("공격속도 : "+공격속도);
    }
}
cs

 

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
32
33
34
35
package day09;
// 어디에 있는 설계도를 가져와서 작업할 것임
// 다른 package에 있기 때문에 불러오기가 필요
// ctrl + shift + O(알파벳)
 
//import day08.Marine;
 
public class TestMain02 {
 
    public static void main(String[] args) {
        // 1. day08.Marine
        Marine m1 = new Marine();
        
        m1.status();
        
        System.out.println();
        
        Marine m2 = new Marine(500100200); // 체력 x y
        m2.status();
        
        System.out.println();
        
        // 체력 공격력 공격속도 이동속도
        Marine m3 = new Marine(20020208);
        m3.status();
        
        System.out.println();
        
        // 체력 x y 공격력 이동속도
        Marine m4 = new Marine(30020010053);
        m4.status();
        
    }
 
}
cs

 

 

* ATM > 접근 지정자, 접근 한정자, 접근 수정자 / 캡슐화 / getter setter

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package day09;
 
// 접근지정자, 접근한정자, 접근수정자
 
// public : 모두에게 허용 된다.
// protected : 동일한 패키지와 상속된 관계 있는 객체만 접근 가능
// default : 동일한 패키지 내에서만 접근 가능
// private : 내 클래스에서만 접근 가능
 
 
//캡슐화(encapsulation)
// 객체의 내부 구조 및 데이터를 캡슐처럼 감싸 외부에서 직접 볼 수 없게
// 은닉하여 보호하는 것
 
// 정보의 은닉
 
public class ATM {
 
//    public String accountNo;
//    protected String name;
    private String accountNo;
    private String name; // 이 변수에 직접적인 접근 막고 메서드를 통한 간접 접근허용
    //
    
    private int balance;
    // 기본생성자 생략했을 경우엔 어떻게 지정된 것과 동일할까요?
    ATM(){
        this.accountNo = null;
        this.name = null;
        this.balance = 0;
    }
    
    public String getName() {
        return this.name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getaccountNo() {
        return this.accountNo;
    }
    
    public void setaccountNo(String accountNo) {
        this.accountNo  = accountNo;
    }
    
    // get변수명()
    // public 자료형 get변수명(){
    //         return this.변수명;
    // }
    // getXXX() ==> getter
    public int getBalance() {
        // 감사기록, .... 권한이 있어?
        // 
        return this.balance;
    }
    
    // public void set변수명(자료형 변수명) {
    //         this.변수 = 변수;
    // }
    // setter
    public void setBalance(int balance) {
        // 감사기록, 권한검사.. db에 저장... 등등
        this.balance = balance;
    }
    
    // 입금기능
    void deposit(int a) {
        balance += a;
        System.out.println(a+ "원 입금합니다");
        System.out.println("현재 잔액: "+balance);
    }
    
    // 출금기능
    void withDraw(int a) {
        // 누구, 얼마나 , 언제 검사 기록을 남길 수 있다.
        
        if(balance >= a) {
        balance -= a;
        System.out.println(a+ "원 출금합니다");
        } else {
            System.out.println("잔액이 부족합니다.");
        }
        System.out.println("현재 잔액: "+balance);
    }
}
cs

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package day09;
 
public class TestMain04 {
 
    public static void main(String[] args) {
        
        ATM atm = new ATM();
        
        // 현재 잔액
        // ???????
        // System.out.println(atm.balance);
        
        // 간접적으로 메서드를 통해서 접근
        System.out.println(atm.getBalance());
        
        System.out.println();
        
        // 5000원 입금
        atm.deposit (5000);        
        
//        atm.balance = 9999999;
        // 변수에 직접적인 수정을 막아 주자.
        
        atm.setBalance(50000);
        
        // 이름을 홍길동 지정 <==
        atm.setName("홍길동");
        
        System.out.println(atm.getName());
        System.out.println();
        
        // 지정메서드 호출
        atm.setaccountNo("1234-5678-123");
        // 출력
        System.out.println(atm.getaccountNo());
        // 계좌번호 : 1234-5678-123
        
        System.out.println();
 
        // 10000원 출금
        atm.withDraw (10000);
        
    }
    
}
cs

 

 

 

* Person > check

 

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package day09;
 
public class Person {
 
    String name;
    int age;
    int eye;
    int nose;
    int mouth;
    String gender;
    String job;
    String tel;
    
 
    public void setage(int age) {
        this.age = age;
    }
    
    public int getage() {
        return this.age;
    }
    
    public void setjob(String job) {
        this.job = job;
    }
    
    public String getjob() {
        return this.job;
    }
    
    // checkAge() 
    // 성인이면 20
    // 15~18 : 15
    // 그 이하면 10을 리턴하는 메서드를 정의
    
    public int checkAge() {
        if (this.age >= 20) {
            return 20;
        } else if(this.age >= 18) {
            return 18;
        } else if(this.age >= 15) {
            return 15;
        } else
            return 10;
    }
    
    
    public Person() {
        eye = 2;
        nose = 1;
        mouth = 1;
        System.out.println("Person 클래스의 기본 생성자");
    }
    
 
    void eating() {
    System.out.println("맛난 걸 먹어요 냠냠");
    }    
    
    void sleeping() {
        System.out.println("쿨쿨~~~");
    }
    
    void talking() {
        System.out.println("쏙닥쏙닥...");
    }
    
    void thinking() {
        System.out.println("나는 생각한다 고로 존재한다...");
    }
    
}
 
cs

 

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
package day09;
 
//import day08.Person;
 
public class TestMain05 {
    public static void main(String[] args) {
        
//         day08.Person p1 = new Person();
        Person p1 = new Person();
        
//        System.out.println(p1.age);
        
        // age변수 setter 사용해서 값 할당
        p1.setage(30);
        
        // age변수 getter 이용해 값 출력
        System.out.println(p1.getage());
        
        // job setter, getter 추가
        p1.setjob("9급 공무원");
        System.out.println(p1.getjob());
        
        
        System.out.println(p1.checkAge());
        
    }
}
cs

 

 

[ 응용 ]

 

 

Q3. 위 클래스에서 멤버변수 int dan 을 추가하고 아래 코드가 가능하도록 클래스를 작성하세요

GuGuDan2 g2 = new GuGuDan2();

g2.dan = 3

​​

g2.print();// 3단 출력

g2.dan = 5

g2.print();// 5단 출력

g2.dan = 9

g2.print();// 9단 출력

package day09;

import java.util.Scanner;

public class GuGuDan2 {

	int dan; // 멤버변수 dan 추가
	
	// 구구단 출력
	void print() {
		for(int i=1;i<=9;i++) {
		System.out.println(dan+" * "+ i +" = " + dan*i);
	}
		System.out.println("---------------");
	}
}
 

 

package day09;

public class Day09Q003 {

	public static void main(String[] args) {

		GuGuDan2 g2 = new GuGuDan2();

		g2.dan = 3;
		g2.print();// 3단 출력 
	
		g2.dan = 5;
		g2.print();// 5단 출력 
		
		g2.dan = 9;
		g2.print();// 9단 출력 

	}
}
 

 

 

4. class와 object 의 차이 ?

> object는 사물, class는 설계도

- 클래스란 '객체를 정의해놓은 것' 또는 클래스는 '객체의 설계도 또는 틀'

- 클래스는 객체를 생성하는데 사용되며, 객체는 클래스에 정의된 대로 생성됨

 

 

5. class를 구성하는 3요소는?

 1) member 변수, 멤버 필드(field)

2) member method

3) 생성자

6. method overloading?

- 다중 정의

- 방법 : method 이름은 동일, 매개변수의 갯수, 순서, 자료형을 다르게 하면 된다.

7. method 호출방법에 따른 분류?

1) call by value : 값을 복사해 주고 호출

2) call by reference : 참조값에 의한 호출-> 참조값을 전달해 주고 호출

 

 

8. 아래의 출력결과를 얻을수 있게 FormatData

클래스를 작성하시오

public class Q08{

public static void main(String[] args){

int a =20;

int[] b = { 10,20,50,30};

float f = 240.3f;

FormatData fd = new FormatData();

fd.print(a);

fd.print(b);

fd.print(f);

}

}

출력결과

---------------------

20

[ 10 20 50 30 ]

240.3

---------------------

package day09;

public class FormatData {

	
	void print(int a) {
		System.out.println(a);
	}
	
	void print(int[] b) {
		System.out.print("[ ");
		for(int i=0; i<b.length; i++) {
		System.out.print(b[i]+" ");
		}
		System.out.print("]");
		System.out.println();
	}
	
	void print(float c) {
		System.out.println(c);
	}
}
 

package day09;

public class Day09Q008 {

    public static void main(String[] args){

        int a =20;

        int[] b = { 10,20,50,30};

        float f = 240.3f;



        FormatData fd = new FormatData();

        fd.print(a);

        fd.print(b);

        fd.print(f);

}
	
}
 

 

 

 

9. 아래 코드가 수행될수 있도록 Student 클래스를 구현하세요

public class Q09 { public static void main(String[] args) { Student s1 = new Student(1, "lee", 80, 90, 60); // 번호 이름 국어 영어 수학 Student s2 = new Student(2, "kim", 70, 80, 90); Student s3 = new Student(3, "hong", 90, 75, 70); Student s4 = new Student(4, "choi", 90, 60, 50); Student s5 = new Student(5, "park", 100, 90, 70); ​ s1.printSum() ; // 총점 s1.printAvg(); // 평균 점수 출력 s2.printSum() ; // 총점 s2.printAvg(); // 평균 점수 출력 s3.printSum() ; // 총점 s3.printAvg(); // 평균 점수 출력 } }

package day09;

public class Student {
// 멤버변수 지정
	int 번호, 국어, 영어, 수학;
	String 이름;

// 생성자
	Student () {
	}
	
// 생성자 오버로딩
	Student(int 번호, String 이름, int 국어, int 영어, int 수학) {
		this();
		this.번호 = 번호;
		this.이름 = 이름;
		this.국어 = 국어;
		this.영어 = 영어;
		this.수학 = 수학;
	}
	
	void printSum() {
		System.out.println(이름 + " 총점 : " +(국어+영어+수학));
	}
	
	void printAvg() {
		System.out.println(이름 + " 평균 : " +(국어+영어+수학)/3);
	}
	
}
 

 

package day09;

public class Day09Q009 {

	public static void main(String[] args) {

		Student s1 = new Student(1, "lee", 80, 90, 60); // 번호 이름 국어 영어 수학
		Student s2 = new Student(2, "kim", 70, 80, 90);
		Student s3 = new Student(3, "hong", 90, 75, 70);
		Student s4 = new Student(4, "choi", 90, 60, 50);
		Student s5 = new Student(5, "park", 100, 90, 70);

		
		s1.printSum() ; // 총점
		
		s1.printAvg(); // 평균 점수 출력
		
		s2.printSum() ; // 총점
		
		s2.printAvg(); // 평균 점수 출력
		
		s3.printSum() ; // 총점
		
		s3.printAvg(); // 평균 점수 출력

	}
}
 

 

 

10. 아래코드가 수행될수 있도록 Phone 클래스를 구성하시오 (다양한 매개변수있는 생성자)

public class Q10 { public static void main(String[] args){ Phone p1 = new Phone("갤럭시S22", "삼성" , 1000000, "010-1111-2222") ; // 폰명, 제조사, 가격, 전화번호 Phone p2 = new Phone("홍미노트", "샤오미","010-2222-3333'); // 폰명, 제조사, 전화번호 Phone p3 = new Phone("아이폰", "애플", "중국","010-3333-4444"); // 폰명, 제조사, 제조국, 전화번호 p1.status(); // member 변수의 현재 값을 출력하는 메서드 p2.status(); p3.stutus(); } }

package day09;

public class Phone {

	// 멤버변수 지정
	String 폰명, 제조사, 전화번호, 제조국;
	int 가격;
	
	// 생성자
	Phone() {
		
	}
	
	// 생성자 오버로딩
	Phone (String 폰명, String 제조사, int 가격, String 전화번호) {
		this.폰명 = 폰명;
		this.제조사 = 제조사;
		this.가격 = 가격;
		this.전화번호 = 전화번호;
	}
	
	Phone (String 폰명, String 제조사, String 전화번호) {
		this.폰명 = 폰명;
		this.제조사 = 제조사;
		this.전화번호 = 전화번호;
	}
	
	Phone (String 폰명, String 제조사, String 제조국, String 전화번호) {
		this.폰명 = 폰명;
		this.제조사 = 제조사;
		this.제조국 = 제조국;
		this.전화번호 = 전화번호;
	}
	
	// 멤버 메서드
	void status() {
		System.out.println("폰명 : "+폰명);
		System.out.println("제조사 : "+제조사);
		System.out.println("전화번호 : "+전화번호);
		System.out.println("가격 : "+가격);
		System.out.println("제조국 : "+제조국);
		System.out.println("--------------------");
	}
}
 

 

package day09;

public class Day09Q010 {

	public static void main(String[] args){

	Phone p1 = new Phone("갤럭시S22", "삼성" , 1000000, "010-1111-2222") ; // 폰명, 제조사, 가격, 전화번호
	Phone p2 = new Phone("홍미노트", "샤오미","010-2222-3333");  // 폰명, 제조사, 전화번호
	Phone p3 = new Phone("아이폰", "애플", "중국","010-3333-4444"); // 폰명, 제조사, 제조국, 전화번호

	p1.status(); // member 변수의 현재 값을 출력하는 메서드
	p2.status();
	p3.status();

	}

}
 

 

 

11. 로또번호 생성기를 구현하시오

public class Q11 {

public static void main(String[] args){

Lotto lt = new Lotto();

lt.print() ; // 로도번호 출력

}

}

출력결과

----------------------------------------------------------------------------

[ 12 , 13 , 19 , 21 , 28, 32, 41]

 

package day09quiz;

import java.util.Arrays;

public class Lotto {


		int[] rnd = new int[45];
		int[] num = new int[6];
			
		Lotto() {
			// 1부터 45까지 값을 배열해 할당
			for(int i=0; i<rnd.length; i++) {
				rnd[i] = i+1;	
		}
		shuffle(rnd);
			
		// 6개의 숫자를 num 배열에 할당
		for(int i = 0; i<6; i++) {
			num[i] = rnd[i];
			}
		
		sort(num); // 정렬
		Arrays.sort(num);
		}
		
		public void sort(int[] a) {
			for(int j=0; j< a.length-1; j++) {
				for(int i = 0; i < a.length-1-j; i++) {
					if(a[i] > a[i+1]) {
					// 값을 교환
					int temp = 0;
					temp = a[i];
					a[i] = a[i+1];
					a[i+1] = temp;
					}
				}
			}
		}
		
		public void shuffle(int[] rnd) {
		// 두 배열 요소끼리 값 교환
			for(int i=0; i<1000; i++) {
				int a = (int)(Math.random()*rnd.length);
				int b = (int)(Math.random()*rnd.length);

				int temp = -100; 
				temp = rnd[a]; 
				rnd[a] = rnd[b]; 
				rnd[b] = temp; 
			}	
		}
			
		public void print() {
			System.out.println(Arrays.toString(num));
		
		}
		
}
 

 

package day09quiz;

public class Day09Q12 {

	public static void main(String[] args) {

		Lotto lt = new Lotto();
		lt.print(); // 로또번호 출력
		
	}

}
 

 

 

 

12. 업그레이드 로또번호 생성기를 구현하시오

public class Q12 {

public static void main(String[] args){

NewLotto lt = new NewLotto(2); // 숫자는 로또 수행횟수 , 2는 2번

lt.print() ;

}

}

출력결과

----------------------------------------------------------------------------

[ 12 , 13 , 19 , 21 , 28, 32, 41]

[ 2, 8, 11, 24, 27 , 31, 44 ]

 

package day09quiz;

import java.util.Arrays;

public class NewLotto {

	int cnt;
	int[] rnd = new int[45];
	int[] num = new int[6];
	
	NewLotto(int cnt) {
		this.cnt = cnt;	
		
	}
	
	public void init(int[] rnd) {
		// 1부터 45까지의 값을 배열에 할당
		for (int i =0;i<rnd.length; i++ ) {
			rnd[i] = i+1;
		}
	}
	
	public void shuffle(int[] rnd) {
	// 두 배열 요소끼리 값 교환
		for(int i=0; i<1000; i++) {
			int a = (int)(Math.random()*rnd.length);
			int b = (int)(Math.random()*rnd.length);

			int temp = -100; 
			temp = rnd[a]; 
			rnd[a] = rnd[b]; 
			rnd[b] = temp; 
		}	
	}
	
	public void set(int[] num, int[] rnd) {
		// 6개의 숫자를 num 배열에 할당
		for(int i = 0; i<6; i++) {
			num[i] = rnd[i];
			}
	}
	
	public void print() {
	
		for(int i=0; i<cnt; i++) {
			
		
		init(rnd);
		
		shuffle(rnd);
		
		set(num, rnd);

		Arrays.sort(num);
		
		System.out.println(Arrays.toString(num));
		}
	}
	
}
 

 

package day09quiz;

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

	
	NewLotto lt = new NewLotto(2);
	lt.print();
}
}