자료구조를 이용한 로또번호 생성
package com.bit.day10;
import java.util.Arrays;
public class Ex11 {
public static void main(String[] args) {
//로또 번호 생성기
//1~45까지 랜덤한 숫자 6개 ---중복되면 안됨.
// 0<= Math.random() < 1 ---연산을 통해 가공해서 써라~
// 0.0 <= Math.random() <10.0 10을 곱하면 0~9 / 20을 곱하면 0~ 19
// 1 <= Math.random() < 11 1을 더하면 1~10
int[] lotto=new int[6];
for(int i=0; i<lotto.length; i++){
//중복값 검출을 해야한다. --> 두번째값이 들어올때 기존값과 검사해서 중복이 나지않으면 다음값 집어넣기.
//세번째값 들어올때 --> 첫번째,두번째와 비교후 중복 없으면 집어넣기.
lotto[i]=((int)(Math.random()*45))+1; //int로 형변환하여 소수점 날리기
}
System.out.println(Arrays.toString(lotto));
}
}
treeset을 이용하면 중복검사+정렬을 할 수 있다.
(마지막에 정렬해서 번호 보여주니까)
public class Ex11 {
public static void main(String[] args) {
//로또 번호 생성기
//1~45까지 랜덤한 숫자 6개 ---중복되면 안됨.
// 0<= Math.random() < 1 ---연산을 통해 가공해서 써라~
// 0.0 <= Math.random() <10.0 10을 곱하면 0~9 / 20을 곱하면 0~ 19
// 1 <= Math.random() < 11 1을 더하면 1~10
Set lotto=new TreeSet();
while(lotto.size()<6){ //6이 되는 순간 빠져나감
lotto.add(((int)(Math.random()*45))+1);
}
Iterator ite = lotto.iterator();
while(ite.hasNext()){
System.out.println(ite.next());
}
}
}
나의 과제 : 배열 / 객체배열로 만들어보기?