これは初めてのことです。私はコーディング方法を学び始めているので、私は正直なところ、この質問が私がここで見つけられるものではないことを願っています! (私はしばらく検索していると約束しますが、私はこの話題のノブなので疑問を解決するために私は理解できないものは見つかりませんでした)。JAVAわからないtry-catch
私は、プログラムが乱数を生成し、生成された数を推測しなければならない単純なゲームをJAVAでやっています。 プレーヤーが数字を入力すると、ゲームはランダムに生成された数字よりも高いか低いかを示すヒントを表示します。
数字だけを入力するとプログラム自体はうまく動作しますが、不正なユーザー入力を処理するtry-catchステートメントを追加します。
私は自分のコードに示すように文を使ってみましたが、なぜ違うのか理解できません。数字の異なるものを入力すると例外がキャッチされ、システムコンソールに表示されます。 out.println()が発生するとプログラムは終了します。
私は例外がキャッチされるたびにプログラムを終了させずに数字を入力することを除いて、try-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'あなた 'から戻った後に終了しますメイン、だからあなたは何を期待しましたか? – tkausl
これをどうやって解決できますか? do-whileステートメントの構造を変更すると、eclipseでエラーがポップアップし、コンパイルできなくなります。 "System.out.println()"の後に "guess = scan.nextInt()"を追加することを考えましたが、動作しません。 – Vicentequesada