LAB - Lotto 프로그램 - HashSet

CODEDRAGON Development/Java

반응형



 

Lotto 프로그램 - HashSet

중복값을 허용하지 않는 HashSet 이용하여 로또 프로그램 만들기

 

 

 


 

 

 

 

 

소스 코드

import java.util.Collections;

import java.util.HashSet;

import java.util.LinkedList;

import java.util.List;

import java.util.Set;

 

public class HashSetLotto {

 

public static void main(String[] args) {

// HashSet 객체 생성

// HashSet <Integer> set = new HashSet<Integer>();

Set <Integer> set = new HashSet<Integer>();

//초기에 Set타입으로 객체생성하여 데이터를 삽입함       

while(set.size() < 6){

// 1~45난수 발생

// hs.add( (int)(Math.random()*45+1) );

int num = (int)(Math.random()*45+1);

set.add(new Integer(num));       

}       

System.out.println(set); //[32, 41, 25, 26, 42, 12]

//정렬하기

//        Collections.sort(set);

//ERROR: The method sort(List<T>) in the type Collections is not applicable for the arguments (HashSet<Integer>)

//Collections.sort는 리스트타입이여서 set타입을 리스트 타입으로 반들어줘야 합니다.

 

//Set -> ArrayList(Collection) -> List (변환방법1)

//Set은 정렬을 못하므로 List타입으로 변환

//        List<Integer> list = new ArrayList<Integer>(set);

//Set -> LinkedList(Collection) -> List (변환방법2)

//LinkedList생성자를 통해 HashSet에 저장된 객체들을 LinkedList에 담아 List타입으로 변환합니다.

List<Integer> list = new LinkedList<Integer>(set);    // LinkedList(Collection c)

System.out.println(list); //[32, 41, 25, 26, 42, 12]

//번호를 크기순으로 정렬하기 위해 Collections클래스의 sort()메소드로 정렬

//sort(List list)는 인자로 List인터페이스 타입만 허용하므로 Set List로 변환한 list

Collections.sort(list);

//정렬 후 로또번호 결과

//정렬기준은 컬렉션에 저장된 객체가 Integer이므로 Integer클래스에 정의된 기본정렬이 사용되었습니다.

System.out.println("\nlotto : " + list); //lotto : [12, 25, 26, 32, 41, 42]

}

}

 

 

/*

[24, 40, 8, 10, 13, 31]

[24, 40, 8, 10, 13, 31]

 

lotto : [8, 10, 13, 24, 31, 40]

 

*/

 

 


반응형