명품 자바 프로그래밍(개정5판) 3장 오픈챌린지 풀이 p.161
import java.util.InputMismatchException;
import java.util.Scanner;
public class CardGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("수를 결정하였습니다. 맞추어 보세요");
int count = 0; // 시도 횟수
int low = 0, high = 99; // low ~ high 사이의 수
int num = (int)(Math.random()*100); // 정답
while(true) {
count++;
System.out.println(low + "-" + high);
System.out.print(count + ">>");
int answer = 0;
try {
answer = scanner.nextInt();
}
catch(InputMismatchException e) {
System.out.println("정수만 입력해주세요.");
scanner.nextLine();
continue;
}
if(answer == num) { // 정답
System.out.println("맞았습니다.");
break;
}
else if(answer > num) { // 입력 값이 더 큰 경우
System.out.println("더 작게");
if(high>answer) high = answer;
}
else { // 입력 값이 더 작은 경우
System.out.println("더 높게");
if(low<answer) low = answer;
}
}
while(true){
System.out.print("다시하시겠습니까(y/n)>>");
String choose = scanner.next();
if(choose.equals("n")) {
scanner.close();
return;
}
else if (choose.equals("y")) {
break;
}
else {
System.out.println("y/n 중에 입력해주세요.");
}
}
}
}
}
개인 풀이이므로 틀린 부분이나 피드백이 있으면 댓글로 남겨주시면 감사하겠습니다!