상세 컨텐츠

본문 제목

[자바] 중복값 없이 로또번호 생성 예제

java

by aries574 2020. 11. 13. 08:38

본문


Math.random() 메소드를 사용하면 랜덤숫자를 얻을 수 있습니다. 

하지만, 중복된 값을 얻을 수도 있습니다. 

HashSet을 사용하면 중복된 데이터 없는 랜덤숫자를 얻을 수 있습니다.

public static void main(String[] args) {

     

     HashSet<String> lottoSet = new HashSet<String>();

     ArrayList<String> arrList = new ArrayList<String>();



     

        while(lottoSet.size() < 7){

          

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

        

         //0이 아닐때만 넣는다.

            if(num != 0){

                lottoSet.add(num+"");

            }

        }



        //set을 list에 담기

        arrList.addAll(lottoSet);



        for(int i=0; i < arrList.size(); i++){

         if(i == 6) {

         System.out.print(arrList.get(i)); 

         }else {

         System.out.print(arrList.get(i)+",");

         }

         

        }

 }

}
반응형

관련글 더보기

댓글 영역