Math. 클래스는 import java.util.Random; 해야 한다.
이 중 Math.random() 은 난수(정의된 범위 내에서 무작위로 추출된 수, 즉 랜덤한 숫자)를 만들어야 할 때 유용하다.
난수는 로또번호 생성이나 추첨기, 암호키 생성 등 추측 불가한 랜덤한 숫자(값)을 뽑아내야 할 때 사용하며 자바에서는 Math.random() 메소드를 통해 만들어 낼 수 있다.
double random = Math.random();
System.out.println("random -> " + random);
/*
random => 0.9656231819446548
random => 0.9172063034242561
*/
Math.random()은 static 메소드이므로 클래스명으로 바로 호출될 수 있으며 double형의 랜덤 숫자를 리턴한다.
숫자의 범위는 0.0이상 1.0"미만"이다.
// 랜덤한 정수 = (int)(Math.random()*구간범위) + 시작값;
int n1 = (int)(random*5); //0~4까지의 숫자를 출력한다.
// => 5는 0,1,2,3,4-> 즉, 0~4까지의 숫자 출력
int n2 = (int)(random*5) + 1; //1~5까지의 숫자를 출력한
다.
//=> 1부터 시작해서 1,2,3,4,5-> 즉, 1~5까지의 숫자 출력
int lottoNumber = (int) (Math.random() * 45) + 1;
//로또 번호 생성기 코드, 1부터 45까지 출력
Math.random()의 리턴타입은 double로, 소수점을 절삭하기 위해 int로 강제 캐스팅하였다(long, short,float 등으로 캐스팅도 가능함)
Random 클래스는 난수와 관련된 메소드들로 구성이 되어 있는 클래스이다. (필드 없음)
Math.random() 보다는 Random 클래스를 사용하는 것이 좀 더 보안적으로 좋으며, 캐스팅 변환 필요없이 인스턴스를 이용해 다양한 타입의 난수를 만들어낼 수 있고 메소드도 다양하여 활용도가 높다.
Random rndom = new Random();
int n1 = rndom.nextInt(10) + 1; //1부터 10까지 중 랜덤
int n2 = rndom.nextInt(7) + 3;
char ch = (char) (rndom.nextInt('z' - 'a' +1) +'a');
// 'a'~'z' 랜덤
System.out.println("1 부터 10 까지 중 랜덤하게 발생한 값 : " + n1);
System.out.println("3 부터 7 까지 중 랜덤하게 발생한 값 : " + n2);
System.out.println("a 부터 z 까지 중 랜덤하게 발생한 소문자 : " + ch);
random.nextInt()는 int 타입의 범위 전체(–2,147,483,648 ~ 2,147,483,647)를 대상으로 한다.
이 때문에 random.nextInt(int bound) 에서 bound는 범위를 지정하는 변수이다.
즉, 0에서 시작한다면 bound -1 까지의 범위를 지정할 수 있다.
뒤의 더하기는 Math.random() 처럼 뽑아낼 숫자의 범위에서 시작하는 숫자를 말한다.
public static void main(String[] args) {
//소문자 3개와 숫자 4개로 이루어진 인증키 만들기
// asa9040 / txa2356
Random random = new Random();
String certification_key = "";
for (int i = 0; i<7; i++) {
if(i < 3) { //랜덤한 소문자 먼저 붙이기
char ch = (char) (random.nextInt('z' - 'a' +1) + 'a');
certification_key += ch;
} else {
int n = random.nextInt(9); // 0~9까지 발생
certification_key += n;
}
}
System.out.println("인증키 : " + certification_key);
}// end of main()-----------------------
/*
============= 메뉴 ==============
1.가위 2.바위 3.보 4.게임종료
================================
>> 선택하세요 => 5엔터
[경고] 메뉴에 존재하지 않는 번호입니다!!
>> 선택하세요 => 똘똘이엔터
[경고] 정수로만 입력하세요!!
>> 선택하세요 => 2
>> 사용자님이 이겼습니다!!^^ 이긴경우
>> 사용자님이 졌습니다ㅜㅜ 진경우
>> 비겼습니다~~ 비긴경우
============= 메뉴 ==============
1.가위 2.바위 3.보 4.게임종료
================================
>> 선택하세요 => 4
>> 프로그램 종료 <<
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random random = new Random();
while (true) {
try {
System.out.println("======= 메뉴 =======");
System.out.println("1. 가위 2. 바위 3. 보 4. 게임종료");
System.out.println("===================");
System.out.println(">> 선택하세요: ");
int select = Integer.parseInt(sc.nextLine());
if (0 >= select || select >= 5){
System.out.println("메뉴에 존재하지 않는 내용입니다!!");
continue;
}
if (select == 4) {
System.out.println("게임을 종료합니다.");
sc.close();
break;
}
// 가위 ㅣ 바위 ㅣ 보 각각 1, 2, 3
// 컴퓨터는 1,2,3 중 랜덤한 숫자 출력
// 만약 사용자가 1(가위)면 2한테 지고 3한테 이기고
// 2(바위)면 1한테 이기고 3한테 지고
// 3(보)면 1한테 지고 2한테 이기고
// 같은 숫자면 비긴다 출력
int computerNumber = random.nextInt(3) + 1; //1부터 3까지
if ((select == 1 && computerNumber == 2) || (select == 2 && computerNumber == 3)
|| (select == 3 && computerNumber == 1)) {
System.out.println("사용자님이 졌습니다");
} else if ((select == 1 && computerNumber == 3) || (select == 2 && computerNumber == 1)
|| (select == 3 && computerNumber == 2)) {
System.out.println("사용자님이 이겼습니다");
} else {
System.out.println("비겼습니다.");
}
} catch (NumberFormatException e) {
System.out.println("정수로만 입력하세요.");
continue;
}
}
}// end of main()----------------------------