숫자 (1-10)을 선택하고 사용자가 추측하는 프로그램을 만드는 프로젝트가 있습니다. 너무 높다면 너무 낮게 추측하면 너무 똑같습니다. 이제 실수를 방지하기 위해 try 블록을 추가해야합니다. 코드를 보면 내가 가지고있는 코드를 볼 수 있지만 코드가 실행되면 catch가 끝납니다. 어떻게 루프백 할 수 있습니까?try-catch를 사용하여 while 루프로 돌아 가기 Java
import java.util.*;
import java.lang.*;
class GuessDR {
public static void main(String[] args){
System.out.println("Welcome to my number guessing game!");
int maxnum = 10;
Scanner input = new Scanner(System.in);
Random rand = new Random();
int number = rand.nextInt(maxnum);
int tries = 0;
int guess;
boolean win = false;
try{
while (win == false){
System.out.println("Guess a number between 1 and "+
maxnum +": ");
guess = input.nextInt();
tries++;
if (guess == number){
win = true;
}
else if(guess < number){
System.out.println("Number is to low, tray again");
}
else if(guess > number){
System.out.println("Number is to high, try again");
}
}
}
catch (InputMismatchException e) {
System.out.println("Enter numerical guess");
}
System.out.println("You win!");
System.out.println("It took you "+ tries + " tries.");
}
}
while 루프 내에서 try-catch 블록을 움직여보십시오. – AJNeufeld
쉬운 방법? 'try'와'catch' 비트를 루프 안으로 이동하십시오. : P – cHao
다음 질문을 기대하면서 (새로운 추측은 계속 'InputMismatchException'을 생성합니다.) [이 질문과 답변] (https://stackoverflow.com/questions/29811339/cannot-figure-out-how-to- catch-inputmismatchexception) – AJNeufeld