[JAVA] Random 클래스

hi·2021년 12월 21일
  1. 랜덤 객체 생성
Random r = new random();
  1. 난수 출력
r.nextInt();  // int타입 모든 범위의 난수 발생

0    <=   r.nextInt(int n)   <   n       : int형 난수 발생
0    <=   r.nextInt(45)      <   45      : 0~44 난수 발생
0+1  <=   r.nextInt(45+1)    <   45+1    : 1~45 난수 발생

👇 랜덤 클래스를 사용한 복권 추첨기

int[] sn = new int[6];     		 // [0,0,0,0,0,0] 
Random r = new Random();   		 // Random 객체 생성

System.out.print("번호 선택>");
	
int i;

for(i=0; i<sn.length; i++) {

	sn[i] = r.nextInt(45)+1; 	// 정수 1~45 중 랜덤으로 배열에 저장	
}

System.out.print(Arrays.toString(sn));  // 난수 출력
System.out.println(); 			
		
		
//당첨번호
int[] winner = new int[6]; 		//[0,0,0,0,0,0] 

Random r2 = new Random();

System.out.print("당첨 번호>");
		
for(i=0; i<winner.length; i++) {

	winner[i] = r2.nextInt(45)+1; 	// 정수 1~45 중 랜덤 배열에 저장
		
}

System.out.print(Arrays.toString(winner));	// 당첨번호
System.out.println(); 			
		
		
// 당첨 여부
System.out.print("당첨 여부>");
if(Arrays.equals(sn, winner)) {

	System.out.println("1등에 당첨되었습니다.");
} else System.out.println("당첨되지 않았습니다.");

0개의 댓글