난수 생성 방법에는 2가지가 있다.
java.util.Random 클래스의 nextInt() 메소드를 이용하여 난수를 발생시킨다.
import java.util.Random;
public class Example1 {
public static void main(String[] args) {
// nextInt(int bound) : 0부터 매개변수로 전달받은 정수 범위까지의 난수를 발생시켜서 정수 형태로 반환
Random random = new Random();
// random.nextInt(구하려는 난수의 갯수) + 난수의 최소값
int rNum1 = random.nextInt(10);
System.out.println("0부터 9까지의 난수: " + rNum1);
// 0부터 9까지의 난수: 5
int rNum2 = random.nextInt(10) + 1;
System.out.println("1부터 10까지의 난수: " + rNum2);
// 1부터 10까지의 난수: 5
// 20부터 45까지의 난수
int rNum3 = random.nextInt(26) + 20;
System.out.println("20부터 45까지의 난수: " + rNum3);
// 20부터 45까지의 난수: 42
//-128부터 127까지의 난수 (256개)
int rNum4 = random.nextInt(256) - 128;
System.out.println("-128부터 127까지의 난수: " + rNum4);
// -128부터 127까지의 난수: 65
}
}
Math.random()을 이용해 발생한 난수는 0이상 1미만까지의 실수 범위의 난수값을 반환한다.
public class Example2 {
public static void main(String[] args) {
// (int) (Math.random() * 구하려는 난수의 갯수) + 구하려는 난수의 최소값
// 0~9
int rMNum1 = (int) (Math.random() * 10);
System.out.println(rMNum1);
// 1~10
int rMNum2 = (int) (Math.random() * 10) + 1;
System.out.println(rMNum2);
// 10~15까지 난수 발생
int rMNum3 = (int) (Math.random() * 6) + 10;
System.out.println(rMNum3);
// -127~128까지 난수 발생
int rMNum4 = (int) (Math.random()*256) - 128;
System.out.println(rMNum4);
}
}
본 포스팅은 멀티캠퍼스의 멀티잇 백엔드 개발(Java)의 교육을 수강하고 작성되었습니다.