Random 클래스는 난수를 생성하는 클래스로 객체를 생성하여 사용한다.
Random 클래스를 사용하는 경우 간단하게 다양한 타입의 난수 생성이 가능하다.
각 타입의 난수 생성을 위한 메소드들은 다음과 같다.
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
Random rand = new Random();
int n = rand.nextInt();
System.out.println(n);
double d = rand.nextDouble();
System.out.println(d);
boolean b = rand.nextBoolean();
System.out.println(b);
int a = rand.nextInt(3);
System.out.println(a);
}
}
실행결과
1137574620
0.5768336912775208
false
1
위의 모든 결과 값들이 주어진 범위내에서 랜덤값을 만들 수 있다.
1~10 사이의 수를 랜덤하게 뽑는 코드
import java.util.Random;
public class RandomTest02 {
public static void main(String[] args) {
Random rand = new Random();
int n = rand.nextInt(10);
System.out.println(n+1);
int s = rand.nextInt();
if (s < 0)
s = s * -1; //음수 양수 변환
s = s % 10 + 1; // 0~9 이기 때문에 + 1
System.out.println(s);
}
}