JAVA/반복문
while문 예제(1)
by pms93
2022. 7. 21.
package loop_while;
import java.util.Random;
import java.util.Scanner;
public class LoopWhileQuiz {
public static void main(String[] args) {
// 1 ~ 100사이의 수 중 랜덤하게 부여된 수를 맞추는 게임
// ex) 사용자의 입력값이 랜덤수보다 낮을경우 up을 출력, 낮을 경우 down을 출력
Random rand = new Random();
Scanner sc = new Scanner(System.in);
int sel, user = 101, com, cnt = 101, tmpCnt;
while (true) {
System.out.print("=== Up & Down Game ===\n1. Game Start\n2. Game Score\n3. Game Exit\n: ");
try {
sel = sc.nextInt();
} catch (Exception e) {
System.out.println("잘못된 입력 형식입니다.");
sc.nextLine();
continue;
}
com = rand.nextInt(100) + 1;
tmpCnt = 0;
if (sel == 1) {
while (user != com) {
while (true) {
try {
System.out.print("<< Player Turn >>\n: ");
user = sc.nextInt();
} catch (Exception e) {
System.out.println("잘못된 입력 형식입니다.");
sc.nextLine();
continue;
}
break;
}
if (user > com)
System.out.println("Down");
else if (user < com)
System.out.println("Up");
tmpCnt++;
}
System.out.println("정답입니다.");
if (tmpCnt < cnt)
cnt = tmpCnt;
}
else if (sel == 2)
System.out.printf("최고 기록은 %d입니다.\n", cnt);
else if (sel == 3){
System.out.println("프로그램을 종료합니다.");
System.exit(0);
}
else
System.out.println("메뉴 확인 후 다시 입력하세요...");
}
}
}