java.util.Random 클래스
난수 발생 전용 클래스
Math 클래스와 달리 인스턴스 생성이 필요함
nextXXX() 메서드를 호출하여 다양한 데이터 타입에 대한 난수 생성 가능
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
32
33
34
35
36
37
38
39
40
41
42
|
Random r = new Random();
for(int i = 1; i<= 10 ; i++) {
nextInt() : int형 데이터 타입 범위 (-21억 ~ +21억) 난수 생성
nextInt(n) : int형 정수 중 0<= x < n 범위의 난수 생성
=> 1 ~ n 사이의 난수를 발생시키는 공식 : nextInt(n) +1
r.nextInt(10)+1 // 1 ~10 사이의 난수
r.nextBoolean // Boolean 타입 난수
r.nextLong() // Long 타입 범위 난수
}
// Random 클래스를 이용한
int dice = r.nextInt(6)+1;
int dice2 = r.nextInt(6)+1;
if(dice != dice2){
System.out.println("첫번째 주사위 : " + dice);
System.out.println("두번째 주사위 : " + dice2);
System.out.println("주사위의 합 : " + (dice+dice2));
}else if(dice == dice2) {
System.out.println("첫번째 주사위 : " + dice);
System.out.println("두번째 주사위 : " + dice2);
System.out.println("한번더 굴리세요"));
}
// Math 클래스 를 이용한 브루마블
int dice3 = ((int) (Math.random() * 6 + 1));
int dice4 = ((int) (Math.random() * 6 + 1));
if (dice3 != dice4) {
System.out.println("첫번째 주사위 : " + dice3);
System.out.println("두번째 주사위 : " + dice4);
System.out.println("두 주사위의 합 : " + (dice3 + dice4));
} else if (dice3 == dice4) {
System.out.println("첫번째 주사위 : " + dice3);
System.out.println("두번째 주사위 : " + dice4);
System.out.println("한 번 더 !");
|
cs |
'Language > Java' 카테고리의 다른 글
enum 타입(열거형 데이터 타입) (0) | 2020.06.24 |
---|---|
BigInteger & BigDecimal (0) | 2020.06.24 |
Math 클래스 (0) | 2020.06.23 |
StringBuffer & StringBuffer 클래스 (0) | 2020.06.23 |
String 클래스의 메서드 (0) | 2020.06.23 |