본문 바로가기
Program/Java

[JAVA] 랜덤한 숫자 맞추기 게임

by C_Meaning 2021. 6. 25.
728x90

자바 코드로 게임을 만들었다.

 

컴퓨터가 제시하는 0~1000 사이의 난수 중 사용자가 숫자를 유추해서 맞추는 게임인데,

 

무턱대고 했을 경우 1000번이나 시도해야하는 상황이 생길 순 없으니, 컴퓨터가 up / down으로 방향성을 알려주는 게임이다.

 

다시할수도 있다.

main 코드

import java.util.Scanner;

public class number_correct {
	
	public static void main(String[] args) {
		
		number_correct_core game = new number_correct_core();
		game.game_core();
		
		Scanner scan = new Scanner(System.in);
		String Question = "";
		int Quest, flag = 0;
		
		do {
			
			System.out.print("다시 하시겠습니까? (Y or N) : ");
			Question = scan.nextLine();
			
			if(Question.equals("Y") || Question.equals("y")) {
				System.out.println("게임을 다시 진행합니다!!");
				game.game_core();
				Question = "";
			}else if(Question.equals("N") || Question.equals("n")){
				System.out.println("안녕히가세요!");
				flag = 1;
			}
			
		}while(flag == 0);		
	}
}

 

game_core 코드

import java.util.Random;
import java.util.Scanner;

public class number_correct_core {
	
	int answer = 0, input_number = 0, count = 0,correct_flag = 0;	
	
	public void game_core() {
		
		Random random = new Random();
		Scanner scan = new Scanner(System.in);
		
		answer = random.nextInt(1000);
		
		System.out.println("랜덤 숫자 맞추기 게임!");
		System.out.print("0 ~ 1000 중에 원하는 숫자를 입력하세요 : ");
		input_number = scan.nextInt();
		
		do{
			count++;
			if(input_number != answer) {
				if(input_number > answer) {
					System.out.println("입력한 숫자는 정답보다 큽니다.");
					System.out.print("다시 입력하기 바랍니다 : ");
					input_number = scan.nextInt();
				}else {
					System.out.println("입력한 숫자는 정답보다 작습니다.");
					System.out.print("다시 입력하기 바랍니다 : ");
					input_number = scan.nextInt();
				}
			}else {
				System.out.println("정답입니다!!");
				System.out.println("총 시도 횟수 : " + count);
				correct_flag = 1;
			}
			
		}while(correct_flag == 0);
	}
}
728x90

댓글