별초롱언니 2025. 5. 15. 17:46

java.util.Random

Random 클래스는 무작위의 값을 얻고 싶을 때 사용합니다. 

 

Random 클래스는 무작위의 값을 추출하기 위한 내부의 알고리즘을 가지고 있습니다. 이 알고리즘에는 종자 값이라는 수가 이용되는데 이 종자 값에 따라 값을 반환하게 됩니다. 만약 기본 생성자로 Random인스턴스를 생성하면 현재의 시간 currentTimeMillis()를 종자 값으로 하여 무작위의 값을 추출합니다. 

package chapter10;

import java.util.Random;

public class exam74 {

	public static void main(String[] args) {
		Random random = new Random();
		Random random2 = new Random(2);
		Random random3 = new Random(2);
		for (int i =0; i < 5; i++) {
			System.out.println("기본 생성자 : " + random.nextInt());
		}
		System.out.println("");
		
		for (int i =0; i < 5; i++) {
			System.out.println("random2 : " + i + "번째 값" + random2.nextInt());
		}
		System.out.println("");
		
		for (int i =0; i < 5; i++) {
			System.out.println("random2 : " + i + "번째 값" + random2.nextInt());
		}
		System.out.println("");
		
		int a = random.nextInt(11)+20; // 20~30 // 11개
		System.out.println(a);
		int b = random.nextInt(100)+100; // 100 ~ 199 // 100개
		System.out.println(b);
		
	}

}