본문 바로가기
Coding/JAVA

[ while문 사용해서 숫자 맞추기 게임 만들기]

by 찡콩찡 2022. 4. 5.
숫자맞추기 게임:7회

사용자 usr 컴퓨터 com 1~100까지의 숫자 중 하나를 입력받는다.
컴퓨터는 1~100까지의 숫자 중 하나를 랜덤하게 형성한다.

user < com :up시켜
user > com : Down시켜
package chapter04;

import java.util.*;

public class Random1 {

public static void main(String[] args) {
Random rand = new Random();
Scanner sc = new Scanner(System.in);
/* int com = (int)Math.random() * 100+1; */

 int com = rand.nextInt(100)+1;  //컴퓨터 랜덤 형성

//시도횟수를 7회까지만 허용하라!
boolean success =false; //성공여부
int tries = 1;

System.out.println("숫자맞추기 게임!도전 기회 7번");

while(true) {  //무한반복
    System.out.println("1~100까지의 숫자를 입력:");
    int user = sc.nextInt(); 
   
    if(tries >= 7)  break;
  if(user == com) 
 {
  success=true;
   break;  //성공시 성공여부를 변경시킨다.
  }
  else if(user > com) System.out.println("Down 시켜봐!");
  else if(user < com) System.out.println("up시켜봐! ");
       tries++;
    }
        //성공 여부에 따른 처리
 if (success ==  true) System.out.println("축하합니다.");
 else                  System.out.println("다시 도전.");
 System.out.println("컴퓨터 생성값:" +com);
}

}