이번이 처음입니다. 나는 코드 작성법을 배우기 시작 했으므로 나는이 질문이 내가 여기에서 찾을 수있는 것이 아니라고 솔직하게 희망한다! (나는 잠시 동안 수색을하겠다고 약속하지만, 나는이 주제의 멍청이이기 때문에 나의 의심을 해결하기 위해 나를 이해할 수있는 것을 찾지 못했다.)자바 이해가 안됨 시도 캐치
Java에서 간단한 게임을하고 있는데, 프로그램에서 임의의 숫자를 생성하고 플레이어가 생성 된 숫자를 추측해야합니다. 플레이어가 숫자를 입력하면 게임은 무작위로 생성 된 숫자보다 높거나 낮 으면 힌트를 표시합니다.
숫자 만 입력하면 프로그램 자체가 제대로 작동하지만 잘못된 사용자 입력을 처리하기 위해 try-catch 문을 추가하려고합니다.
나는 내 코드에서 보여준대로 문장을 사용했지만, 왜 다른 숫자를 입력 할 때 예외가 발생하여 시스템 콘솔에 출력되기 때문에 왜 제대로 작동하지 않는지 이해할 수 없다. out.println(),이 때 프로그램이 종료됩니다.
예외가 catch 될 때마다 프로그램을 종료하지 않고 번호를 입력하는 것만을 시도하려고합니다. 어떻게 해결할 수 있습니까?
도움을 주셔서 감사합니다.
import java.util.Scanner;
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in); //Creates Scanner object to read from keyboard
String playAgain = ""; //if == y, game restarts
try {
do {
// Create a random number for the user to guess
int theNumber = (int)(Math.random() * 100 + 1);
//System.out.println(theNumber); //Uncoment this in case we want to know the number (for testing).
int guess = 0; //Number entered by the player
int count = 0; //Number of tries of guessing the number
while(guess != theNumber){
System.out.println("Guess a number between 1 and 100:");
guess = scan.nextInt(); //Reads the number typed on the keyboard by the player
count++; //Plus 1 every time a number is entered
System.out.println("You entered " + guess +".");
if(guess < theNumber) { //If number entered is smaller
System.out.println("The number is bigger" + ", try again!");
System.out.println("Number of tries: " + count);
} else if(guess > theNumber) { //If number entered is bigger
System.out.println("The number is smaller" + ", try again!");
System.out.println("Number of tries: " + count);
} else { //If both previous cases are false
System.out.println("Congratulations! You've found the number!");
}
}
//Once guess == theNumber
System.out.println("Number of tries: " + count);
System.out.println("Play again? (y/n)");
playAgain = scan.next(); //Reads the String entered from keyboard by the player
}
while(playAgain.equalsIgnoreCase("y")); //If player enters y, start again.
//Otherwise
System.out.println("Thank you for playing! Goodbye :)");
} catch (Exception e) {
System.out.println("Incorrect entering! Please enter a number between 1 and 100.");
}
scan.close(); //Close scanner
} //Close main
} //Close class
프로그램 때문에 스캐너를 폐쇄하고있어 catch' 당신'에서 복귀 한 후 종료 main, 그래서 당신은 무엇을 기대 했습니까? – tkausl
그러면 어떻게 해결할 수 있습니까? do-while 문 구조를 수정하면 Eclipse에서 오류가 발생하고 컴파일을 허용하지 않습니다. "System.out.println()"다음에 "guess = scan.nextInt()"를 추가하려고 생각했지만 작동하지 않습니다. – Vicentequesada