랜덤 값 가져오기 - Math.random(), Random.class
랜덤 값 가져오기 - Math.random(), Random.class
1. Math 유틸 클래스의 random() 메서드 사용
Math.random()사용 하기.
- 반환값은 double 타입이고 0.0 에서 1.0사이의 랜덤한 값이 반환된다.
0.0 <= 임의의 난수 < 1.0
1
2
3
4
public static void main(String[] args) {
double a= Math.random();
System.out.println(a);
}
특정 범위의 값 지정하기
(int)(Math.random()*(구간범위)) + 시작 값
- 구간범위 => 최대 값 - 최소 값 + 1
1
2
3
4
5
public static void main(String[] args) {
//2부터 5까지 중 랜덤한 정수
int d = (int) (a*(5-2+1))+2;
System.out.println(d);
}
2. Random 클래스 사용
Random random = new Random();random.nextInt();으로 사용.
- 구간 범위 공식은 똑같다.
random.nextInt(최대 값 - 최소 값 + 1) + 시작 값- Math.random() 보다 Random 클래스 사용이 권장됨!
1
2
3
4
5
6
public static void main(String[] args) {
//2부터 5까지 랜덤한 정수
Random random = new Random();
int aa = random.nextInt(5 - 2 +1 ) + 2;
System.out.println(aa);
}
1
2
3
4
5
6
public static void main(String[] args) {
//a 부터 z 사이의 임의의 알파벳
Random random = new Random();
char bb = (char) (random.nextInt('z' - 'a' +1)+'a');
System.out.println(bb);
}
3. Random 값을 활용한 가위 바위 보 구현
종료 일때는 바로 종료 시켜 버릴거니까 그냥 while 문에 break 쓰는 로직으로 짜는게 더 좋을 것 같다.
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class RockScissorsPaperMain {
private static int getRandomResult (Random random) {
return random.nextInt(3-1+1)+1;
}
public static void main(String[] args) {
Random random = new Random();
Scanner sc = new Scanner(System.in);
boolean myExit = false;
int userInput = 0;
do {
System.out.println("=================메뉴==============\n"
+ "1.가위\t2.바위\t3.보\t4.게임종료\n"
+ "==================================");
System.out.print("입력해 [1 ~ 4] : ");
try {
userInput = Integer.parseInt(sc.nextLine());
if( !(userInput>=1&&userInput<=4) ) throw new NumberFormatException();
}catch(NumberFormatException e) {
System.out.println("메뉴에 없는 번호임 1 부터 4까지만 입력해");
}
int computerResult = getRandomResult(random);
if(userInput == 4) {
myExit = true;
break;
}
int result = computerResult - userInput;
String resultStr = null;
if(result == 0 ) resultStr = "비김";
else if (result == -1||result == 2) resultStr = "이김";
else if (result == -2||result == 1) resultStr = "짐";
System.out.printf("\n=============결과 : %s ============\n", resultStr);
String c = switch(computerResult) {
case 1 -> "가위";
case 2 -> "바위";
case 3 -> "보";
default -> null;
};
String u = switch(userInput) {
case 1 -> "가위";
case 2 -> "바위";
case 3 -> "보";
default -> null;
};
System.out.println("\t컴퓨터 : "+ c+", 유저 : "+u+"\n");
}while(!myExit);
sc.close();
System.out.println("==================종료===============");
}
}
이 작성글은 저작권자의 CC BY 4.0 라이센스를 따릅니다.

