Java/기타 알고리즘

난수를 맞히는 게임

은찡안찡 2023. 4. 5. 17:46

- 문제 > 난수를 맞히는 게임

package com.dream.controls;

import java.util.Scanner;

public class OverLapEx08 {
	public static void main(String[] args) {
		//1. 1부터 100까지의 난수를 발생시켜 randomNum 변수에 담는다.
		Scanner scan = new Scanner(System.in);
		int randomNum = (int)(Math.random()*100)+1;
		int inputNum = 0;
		//Math.random(): 0.0 ~ 0.999...
		//Math.random()*100: 0.0 ~ 99.999...
		//(int)(Math.random()*100): 0 ~ 99
		//(int)(Math.random()*100)+1: 1 ~ 100
		//2. 사용자로 부터 정수를 입력받는다.
		System.out.println("===== 난수를 맞히는 게임 =====");		
		
		//3. 사용자가 입력한 정수와 난수를 무한 비교하여 메시지를 출력한다.
		//"입력한 정수가 난수 보다 크다." 또는 "입력한 정수가 난수보다 작다."
		while(true) {
			System.out.print("정수 입력: ");
			inputNum = scan.nextInt();
			
			if(inputNum == randomNum) {
				System.out.println("난수 값을 맞혔습니다.");
				break; //무한 반복문을 벗어난다.
			}else if(inputNum > randomNum) {
				System.out.println("입력한 정수가 난수 보다 크다.");
			}else {
				System.out.println("입력한 정수가 난수보다 작다.");
			}
		}
	}
}