java공부

자바/java Random 난수 메소드 이용과 Math이용

이쟤키 2021. 7. 20. 00:31
반응형

java.util.Random

import java.util.Random

Random r = new Random();
//int num = rnd.nextInt(); // 범위를 지정하지 않으면, 정수범위내에서 난수 추출
//int num = rnd.nextInt(10); // 경우의 수 - 10가지(0 ~ 9)
//int num = rnd.nextInt(10) + 1; // 1 ~ 10
int num = rnd.nextInt(20) + 11; // 11 ~ 30
		
double n = rnd.nextDouble(); // 0.0 이상 1.0 미만의 실수를 리턴

java.lang.Math.random()

double n = Math.random(); // 0.0 이상 1.0 미만의 실수를 리턴	
//int num = (int)(Math.random() * 10) + 1; // 1 ~ 10 사이의 정수
//int num = (int)(Math.random() * 20) + 11; // 11 ~ 30 경우의 수 20 최소값 11
boolean bool = (int)(Math.random() * 2) == 0; // true false