Notice
Recent Posts
Recent Comments
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

DeFacto-Standard IT

[Java] Math.random() 랜덤으로 숫자, 문자 얻기 본문

Java/Basic

[Java] Math.random() 랜덤으로 숫자, 문자 얻기

defacto standard 2017. 9. 19. 00:24

0.0 <= Math.random() < 1.0 범위의 double 값을 리턴한다.

 

<범위 내의 랜덤 숫자 얻기>
따라서 1과 10 사이의 랜덤한 정수를 구하고 싶다면

(int) (Math.random() * 10) +1  로 구하면 된다.

 

이는 다음과 같은 과정을 거친다.

 

1. 발생시키는 수가 총 10개 이므로 10을 곱함

0.0 * 10 <= Math.random() * 10 < 1.0 * 10

 : 0.0 <= Math.random * 10 < 10.0

 

2. 정수를 뽑아내야 하므로 int로 변환

(int) 0.0 <= (int) (Math.random * 10) < (int) 10.0

 : 0 <= (int) Math.random * 10) < 10

 

3. +1

0 + 1 <= (int) (Math.random() * 10) + 1 < 10 + 1

 : 1 <= (int) (Math.random() * 10) + 1 < 11

 

비슷한 방법으로 주사위(1~6) 등을 구현할 수도 있다.

 

 

<범위 내의 랜덤 문자 얻기>

 

문자 역시도 활용이 가능하다. 영문 대문자 26개('A' ~ 'Z')의 코드값은 65~90이다.

 

(char) Math.random() * 26 + 65 로 구하면 된다.

 

1. 발생시키는 수가 총 26개 이므로 26을 곱함

0.0 * 26 <= Math.random() * 26 < 1.0 * 26

 : 0.0 <= Math.random * 26 < 26.0

 

2. 65부터 시작하므로 65를 더한다. 65는 'A'에 해당하므로 이를 더해도 상관없다.

0.0 + 65 <= Math.random() * 26 + 65 < 26.0 + 65

 : 65.0 <= Math.random() * 26 + 65 < 91.0

 

3. char로 Casting

(char) 65.0 <= (char) Math.random() * 26 + 65 < (char) 91.0

 : 'A' <= (char) Math.random() * 26 + 65 < '['

 

*참고로 '['는 'Z' 보다 코드값이 1이 더 큰 문자

 

 

Comments