JAVA - while(true) switch-break문을 이용한 Up&Down 게임 (2022-07-18)
2022. 7. 19. 01:29ㆍ3층 1구역 - 개발의 장/JAVA
package loop_while;
import java.util.Random;
import java.util.Scanner;
public class Quiz07_Teach {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int bestScore = 0;
while (true) {
System.out.println("=== Up & Down Game ==");
System.out.println("1. Game Start");
System.out.println("2. Game Score");
System.out.println("3. Game Exit");
System.out.print(">> ");
String select = sc.next();
switch(select) {
case "1":
System.out.println("<< Game Start >> ");
Random r = new Random(); //랜덤으로 수를 생성.(난수 지정)
int com = r.nextInt(100) + 1; // 난수는 1~100사이로 생성한다.
System.out.println("com : " + com); //맞춰야 하는 숫자
int currentScore = 0; //게임 진행횟수 초기화 선언
while(true){
currentScore++; // 게임이 진행되면 진행 횟수 1 추가
System.out.println("<< player turn >> ");
System.out.print("input number : ");
int user = 0;
try {
user = sc.nextInt(); //사용자가 숫자 이외에 다른 문자열을 입력할 때 예외발생을 처리
} catch (Exception e) {
System.out.println("숫자를 입력하세요.");
sc.nextLine();
continue; //메세지 출력 후 다시 데이터 입력으로 돌아감.
}
if(user < 1 || user > 100) { //사용자가 1~100 범위 이외의 숫자를 선언할 때 메세지 출력
System.out.println("입력 범위는 1 ~ 100 입니다.");
continue; // 메세지 출력 후 다시 데이터 입력으로 돌아감.
}
if(user > com)
System.out.println("Down!!");
else if(user < com)
System.out.println("Up!!");
else {
System.out.println("플레이어가 정답을 맞췄습니다.!!");
if(bestScore > currentScore || bestScore == 0) {
bestScore = currentScore; //진행횟수 = 최고기록
}
break;
}
}
break;
case "2": System.out.println("최고 기록은 " + bestScore + "번 입니다.");
break;
case "3": System.out.println("프로그램을 종료합니다."); System.exit(0);
default : System.out.println("메뉴를 확인 후 다시 입력하세요.");
}
}
}
}
'3층 1구역 - 개발의 장 > JAVA' 카테고리의 다른 글
JAVA - while(true) switch-break문을 이용한 컴퓨터와 함께하는 Up&Down 게임 (2022-07-18) (0) | 2022.07.19 |
---|---|
JAVA - while(true) switch-break문을 이용한 다이스 롤! 게임 (2022-07-18) (0) | 2022.07.19 |
JAVA - while(true)와 switch-break문을 이용한 가위 바위 보! 게임 (2022-07-18) (0) | 2022.07.19 |
JAVA - 동전 앞, 뒷면 맞추는 퀴즈 (0) | 2022.07.17 |
JAVA - 회원가입하고 로그인하는 퀴즈 (0) | 2022.07.17 |