這是我在StackOverflow中的第一個問題,所以我希望你能原諒我在設置這篇文章時可能會遇到的許多錯誤.... 我的問題如下:這段代碼應該生成一個隨機數,將其顯示給用戶(爲了幫助我猜測它沒有做太多的嘗試......這應該只是一個練習),要求用戶猜測0到50之間的數字,檢查輸入是否爲整數,如果用戶猜到正確的數字,則輸出「是,數字是..」。 但是,如果用戶輸入了一個字母或任何不是數字的數字,那麼if/else循環變得瘋狂並且程序開始打印「選擇0到50之間的數字:請插入0到50之間的數字,而不是一個字母「沒有停止... 可以幫助我嗎?Java:在while循環中嵌套一個if/else語句
package methods;
import java.util.Scanner;
public class Methods {
static int randomNumber;
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println(getRandomNum());
int guessResult = 1;
int randomGuess = 0;
while (guessResult != -1) {
System.out.print("Choose a number between 0 and 50: ");
if (userInput.hasNextInt()) {
randomGuess = userInput.nextInt();
guessResult = checkGuess(randomGuess);
} else {
System.out.println("Please insert a number, not a letter");
}
}
System.out.println("Yes, the number is " + randomGuess);
}
public static int getRandomNum() {
randomNumber = (int) (Math.random() * 51);
return randomNumber;
}
public static int checkGuess(int guess) {
if (guess == randomNumber) {
return -1;
} else {
return guess;
}
}
}
@ChicagoRedSox它不會幫助算法修改else分支中的guessResult。 – laune
@ChicagoRedSox不會解決他的問題。在提示錯誤後,他想繼續詢問輸入。他需要讀取字符串不讀整數 –