1. Java.util.Random
로또 프로그램 제작
* 길이 6인 int형 배열 생성하고 1~45 숫자 범위로 난수를 구함.
* 중복되지 않는 6개의 숫자를 생성해서 배열에 저장하고 출력하시오.
* 난수 생성 : Math.random() 또는 Random 클래스의 nextInt()메서드 사용
1) 로또 번호가 중복되는 경우
Random random = new Random(); -> 랜덤 객체 생성
package kr.s28.lang.math;
import java.util.Arrays;
import java.util.Random;
public class RandomMain03 {
public static void main(String[] args) {
//로또 번호를 저장할 배열 생성
int[] lotto=new int[6];
Random random = new Random();
System.out.print("로또 번호 : ");
for(int i=0; i<lotto.length;i++) {
lotto[i]= random.nextInt(45)+1; //1~45
}
//확장 for문을 이용한 출력
for(int num : lotto) {
System.out.print(num+ "\t");
}
}
}
2) 로또 번호가 중복되지 않는 경우
오름차순 정렬
Arrays.sort(lotto)
package kr.s28.lang.math;
import java.util.Arrays;
import java.util.Random;
public class RandomMain03 {
public static void main(String[] args) {
//로또 번호를 저장할 배열 생성
int[] lotto=new int[6];
Random random = new Random();
for(int i=0; i<lotto.length;i++) {
lotto[i]= random.nextInt(45)+1; //1~45
// 중복된 숫자가 있는지 검증
for(int j=0;j<i;j++) {
if(lotto[i]==lotto[j]){//값 중복
System.out.println("~~~~"+lotto[j]);//중복된 값 출력
i--;//다음 루프로 넘어가지 못하고 현재 루프에서 새로 값을
//입력할 수 있도록 처리
break;
}
}
}
//오름차순 정렬
Arrays.sort(lotto);
//확장 for문을 이용한 출력
for(int num : lotto) {
System.out.print(num+ "\t");
}
}
}
2. Math.random
- Math.random() 함수는 double 형으로 0.0이상 1.0 미만 사이의 값을 반환하는 함수이다.
- 0.xxxxxx ~ 0.9xxxxxx 값 반환
- int 로 정수화시켜줘야 한다.
- 랜덤함수는 0부터 나오기 때문에 1부터의 값을 뽑고 싶다면 +1 해줘야 한다.
package kr.s28.lang.math;
import java.util.Random;
public class test1 {
public static void main(String[] args) {
int[] lotto=new int[6];
Random random = new Random();
System.out.println("로또 번호 : ");
for(int i=0; i<lotto.length;i++) {
lotto[i]= (int)(Math.random()*45+1);
for(int j=0;j<i;j++) {
if(lotto[i]==lotto[j]){
i--;
}
}
System.out.print(lotto[i]+" ");
}
}
}
'개인 공부 > 자바&Oracle' 카테고리의 다른 글
자바 4장 배열 (0) | 2023.09.10 |
---|---|
23.09.03 자바 복습 (0) | 2023.09.04 |