1. random문이란?
1. Math.random() : 간단하지만 실수(double)만 변환
2. java.util.Random 클래스 : 다양한 지원 타입 지원
예시 1 : Math.random()
// 0.0 이상 1.0 미만의 실수
double randDouble = Math.random();
System.out.println("실수 랜덤값: " + randDouble);
// 1부터 10 사이의 정수
int randInt = (int)(Math.random() * 10) + 1;
System.out.println("정수 랜덤값 (1~10): " + randInt);
import java.util.Random;
public class Main {
public static void main(String[] args) {
Random rand = new Random();
// 0.0 이상 1.0 미만의 실수
double randDouble = rand.nextDouble();
System.out.println("실수 랜덤값: " + randDouble);
// 1부터 10 사이의 정수
int randInt = rand.nextInt(10) + 1;
System.out.println("정수 랜덤값 (1~10): " + randInt);
}
}
2. 기본 예제
import java.util.Random;
public class LottoExample {
public static void main(String[] args) {
Random rand = new Random();
int lottoNumber = rand.nextInt(45) + 1; // 1~45
System.out.println("로또 번호: " + lottoNumber);
}
}
import java.util.Random;
public class MenuExample {
public static void main(String[] args) {
String[] menus = {"김치찌개", "제육볶음", "된장국", "비빔밥", "불고기"};
Random rand = new Random();
String todayMenu = menus[rand.nextInt(menus.length)];
System.out.println("오늘의 추천 메뉴: " + todayMenu);
}
}
< menus[rand.nextInt(menus.length) >
- rand.nextInt(menus.length)는 0부터 menus.length - 1 사이의 정수를 랜덤으로 뽑음.
3. 자주 하는 실수 Top 2
int num = (int)(Math.random() * 10); // 0~9 (❌ 1 포함 X)
해결법 :
int num = (int)(Math.random() * 10) + 1; // ✅ 1~10
String[] arr = {"a", "b", "c"};
Random rand = new Random();
String s = arr[rand.nextInt(3 + 1)]; // ❌ IndexOutOfBounds
해결법 :
String s = arr[rand.nextInt(arr.length)]; // ✅ 안전하게 0~2
아따리!!!!!! 기본 예제와 자주 하는 실수까지...... 유얼이스빛.....