メインコンテンツまでスキップ

랜덤한수(난수) 구하기

자바에서 랜덤한 수(난수)를 구할 때 Math.random()을 사용한다.

기본사용

public class Exercise {
public static void main(String[] args) {

for (int i = 0; i < 5; i++) {
System.out.println(Math.random());
}
}
}
0.37803757646810754
0.012280375167830981
0.11508364112779268
0.23456413483868432
0.7836832352304851

0.0 ~ 1.0 사이의 수를 랜덤하게 보여준다.

Math.random()의 결과값은 double이 기본형이다.

public class Exercise {
public static void main(String[] args) {

for (int i = 0; i < 5; i++) {

double doubleData = Math.random();

System.out.println(doubleData);
}
}
}
0.19360292500547283
0.1012195645034566
0.6995575309133965
0.8818871337380098
0.5343439490349642

참고로 double 형의 범위. (float / double은 실수형이다)

  • 크기(byte/bit) : 8 / 64
  • 4.9E-324 ~ 1.7976931348623157E308

int 형으로 구하기

public class Exercise {
public static void main(String[] args) {

double doubleData = Math.random();

int intData1 = (int) doubleData * 10;

int intData2 = (int) Math.random() * 10;

int intData3 = (int) (doubleData * 10);

int intData4 = (int) (Math.random() * 10);


System.out.println("램덤으로 나온 값 : " + doubleData);

System.out.println("괄호 안침(intData1) : " + intData1);
System.out.println("괄호 안침(intData2) : " + intData2);


System.out.println("괄호침 : " + intData3);
System.out.println("괄호침(새로랜덤구한값) : " + intData4);

}
}
램덤으로 나온 값 : 0.8410611294981729
괄호 안침(intData1) : 0
괄호 안침(intData2) : 0
괄호침 : 8
괄호침(새로랜덤구한값) : 3

형변환 하겠다고 앞에 (int)만을 붙혀주는 일은 없도록... -_-;;;

0 ~ 10 사이의 정수 / 0 ~ 100 사이의 정수

public class Exercise {
public static void main(String[] args) {

for (int i = 0; i < 3; i++){
int randomInt = (int)(Math.random()*10);
System.out.println("0 ~ 10 사이의 정수 : " + randomInt);
}

for (int i = 0; i < 3; i++){
int randomInt = (int)(Math.random()*100);
System.out.println("0 ~ 100 사이의 정수 : " + randomInt);
}
}
}
0 ~ 10 사이의 정수 : 0
0 ~ 10 사이의 정수 : 6
0 ~ 10 사이의 정수 : 2
0 ~ 100 사이의 정수 : 44
0 ~ 100 사이의 정수 : 41
0 ~ 100 사이의 정수 : 74

(Math.random()*10) 식으로 0하나씩 더해서 붙혀주면 얼마든지 0 ~ 원하는 자릿수대의 랜덤한 수를 얻을 수 있다.

덤으로 Random 클래스

public class Exercise {
public static void main(String[] args) {

Random random = new Random(); //랜덤 객체 생성(디폴트 시드값 : 현재시간)
random.setSeed(System.currentTimeMillis()); //시드값 설정을 따로 할수도 있음

System.out.println("0이상 n이하의 랜덤한 정수값 : " + random.nextInt(10));
System.out.println("랜덤 boolean 값 : " + random.nextBoolean());
System.out.println("랜덤 long 값 : " + random.nextLong());
System.out.println("랜덤 float 값 : " + random.nextFloat());
System.out.println("랜덤 double 값 : " + random.nextDouble());
System.out.println("랜덤 정규 분포의 난수 값 :" + random.nextGaussian());

}
}
0이상 n이하의 랜덤한 정수값 : 4
랜덤 boolean 값 : false
랜덤 long 값 : -6335266456639445019
랜덤 float 값 : 0.36527854
랜덤 double 값 : 0.1667894559247396
랜덤 정규 분포의 난수 값 :1.2599487147485253

로또 번호 출력

public class Exercise {
public static void main(String[] args) {

Random rd = new Random();//랜덤 객체 생성

for(int i=0;i<6;i++) {
System.out.print("["+(rd.nextInt(45)+1)+"]"); //로또번호 출력
}

}
}
[20][39][11][21][20][23]