안녕하세요, 여행벌입니다.

오늘은 자바 랜덤 난수 생성하는 2가지 방법에 대해서 포스팅해보겠습니다.


java.util.Random 클래스 이용

Random 클래스를 이용하면 여러 가지 자료형에 대해서 랜덤 난수를 생성할 수 있습니다.

( import를 해줘야 사용할 수 있습니다. )

random.nextBoolean(); // true 아니면 false를 생성
random.nextInt(); // Int 형 범위에서 정수를 랜덤하게 생성
random.nextInt(N); // 0 ~ N - 1 범위에서 정수를 랜덤하게 생성
random.nextLong(); // Long 형 범위에서 정수를 랜덤하게 생성
random.nextFloat(); // 0.0F ~ 1.0F 사이에서 실수를 랜덤하게 생성
random.nextDouble(); // 0.0D ~ 1.0D 사이에서 실수를 랜덤하게 생성

 가장 자주 쓰이는 메소드는 nextInt() 함수로 매개변수를 통해 범위를 지정할 수 있습니다.

 물론, 이 난수들은 유사 난수(Pseudo Random Number)입니다. 즉, 컴퓨터가 가지고 있는 랜덤 알고리즘에 의해서 생성되는 난수들이지 정말 랜덤하게 생성되는 수는 아닙니다. 

package Hello;
import java.util.Random;

public class randomTest {
	public static void main(String args[]) {
		Random random = new Random();
		System.out.println("nextBoolean : " + random.nextBoolean());
		System.out.println("nextInt : " + random.nextInt());
		System.out.println("nextInt : " + random.nextInt(100));
		System.out.println("nextLong: " + random.nextLong());
		System.out.println("nextFloat : " + random.nextFloat());
		System.out.println("nextDouble : " + random.nextDouble());
	}
}
// Console
nextBoolean : true
nextInt : 540532811
nextInt : 15
nextLong: -1389414493932819308
nextFloat : 0.20302159
nextDouble : 0.44444974642727286

java.lang.Math 클래스 이용

 Math 클래스는 java.lang 패키지에 있으므로 별도로 import 할 필요는 없습니다. 또, Math 클래스의 random() 메소드는 Static 메소드이므로 객체를 생성하지않고 사용할 수 있습니다.

 Math.random() 메소드는 0.0D ~ 1.0D 난수를 발생합니다.

package Hello;

public class randomTest {
	public static void main(String args[]) {
		System.out.println("Math 클래스 난수 : " + Math.random());
	}
}
Math 클래스 난수 : 0.9956712501922751

 그럼 Math.random() 함수를 이용해서 0 ~ 9 사이의 숫자를 랜덤하게 얻고 싶으면 어떻게 해야 할까요?

package Hello;

public class randomTest {
	public static void main(String args[]) {
		System.out.println("Math 클래스 난수(0~9사이 정수 난수발생) : " + (int)(10*Math.random()));
	}
}

 다음과 같이 10을 곱해주고 강제 형 변환을 통해 소수점 뒤의 숫자들을 날려주면 됩니다.


 

+ Recent posts