본문 바로가기
안 씀/java-예제&실습

[명품자바] 3장 오픈챌린지

by unhyepnhj 2024. 6. 19.

숨겨진 카드의 수를 맞추는 게임을 만들어보자

 

0에서 99까지 임의의 수를 가진 카드를 한 장 숨기고 이 카드의 수를 맞추는 게임

숨겨진 수보다 더 낮은 수가 입력되었을 경우 "더 높게" 출력

더 높은 수가 입력되었을 경우 "더 낮게" 출력

범위를 좁혀가며 수를 맞춤 

정답을 찾았을 경우 게임을 반복할지 질문(yes/no)

y일 경우 반복, n일 경우 종료

 

이중 반복문을 사용하라네요

난수 생성을 위해 Random 클래스도 사용해야 할 것 같습니다(import java.util.Random)

Random 클래스의 nextInt() 메소드 참고

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

public class CardGame {
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		while(true) {
			int min=0, max=99;	//양 끝값 0, 99로 초기화
			int index=1;	//반복 횟수

			Random r=new Random();
			int randNum=r.nextInt(100);	//0~99까지 난수 생성
			System.out.println("수를 결정하였습니다. 맞추어 보세요");
			while(true) {
				System.out.println(min+"-"+max);
				System.out.print(index+">>");
				int input=scanner.nextInt();
				
				if(input==randNum) {
					System.out.println("맞았습니다.");
					break;
				}
				else if(input>randNum) {
					System.out.println("더 낮게");
					max=input;
				}
				else{
					System.out.println("더 높게");
					min=input;
				}
			}//end of while
			System.out.print("다시하시겠습니까? (yes/no) >> ");
			if(scanner.next().equals("no")) break;
		}//end of while
		scanner.close();
	}
}

 

>>실행