🙈

⃝ 동글동글 ⃝

🪐ᐩ˖ 🍎

Java/기초

[Java 기초] Random 클래스

JONG_UK 2023. 5. 20. 00:23
728x90
반응형
SMALL

Random 클래스

 

Math.random() 메서드와 같이 난수를 생성할 수 있는 java.util.Random 클래스가 존재한다.

// 두 코드는 동등하다.
int num = (int)(Math.random() * 6) + 1;
int num = new Random().nextInt(6) + 1;

Math.random() 메서드는 내부적으로 Random 클래스의 인스턴스를 생성해서 사용하는 것이기 때문에 위의 코드 중 편한 것을 사용하면 된다.

Math.random() 메서드와 Random 클래스가 다른 점은 종자값(seed) 시드를 설정할 수 있다는 것이다. 종자값을 설정하면, Random 인스턴스들은 모두 항상 같은 난수를 순서대로 반환하게 된다. 

 

import java.util.*;

class RandomEx1 {
	public static void main(String args[]) {
		Random rand  = new Random(1);
		Random rand2 = new Random(1);

		System.out.println("= rand =");
		for(int i=0; i < 5; i++)
			System.out.println(i + ":" + rand.nextInt());

		System.out.println();
		System.out.println("= rand2 =");
		for(int i=0; i < 5; i++)
			System.out.println(i + ":" + rand2.nextInt());
	}
}

 

사용하는 것에 대해서는 크게 어렵지 않다. 종종 사용하게 될 일이 있을 테니 알아두자!

728x90
반응형
LIST