首先,我很抱歉如果我正在複製郵件。我試圖尋找解決方案,並找不到它。我正在製作一個等級計算器,用戶通過掃描儀輸入雙倍「x」的時間。我已經瞭解了它的基本原理,並且我沒有試圖解決用戶在輸入數字時可能遇到的任何問題。如何檢查掃描儀輸入是否是整數,如果是,從循環中斷開
public static void main(String args[]) {
double total = 0;
int counter = 0;
ArrayList<String> answerYes = new ArrayList<>();
answerYes.add("yes");
answerYes.add("y");
answerYes.add("yea");
Scanner answerCheck = new Scanner(System.in);
System.out.println("Would you like to submit a number to calculate the average? [y/n]");
String userInput = answerCheck.nextLine();
while (answerYes.contains(userInput)) {
Scanner numberInput = new Scanner(System.in);
System.out.println("Please input a number: ");
Integer number = numberInput.nextInt(); //Here is where I need to check for a non-integer.
total += number;
System.out.println("Would you like to submit another number to calculate the average? [y/n]");
userInput = answerCheck.nextLine();
counter++;
}
double average = total/counter;
System.out.println("The average of those numbers is: " + average);
}
我敢肯定我做了這個複雜得多,這一點也可以,但我想測試我的能力,使平均計算的方式我就沒有互聯網。希望我正確地格式化了這個。
感謝, 喬丹
[驗證使用java.util.Scanner中輸入(https://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – Tom
'nextInt的可能的複製()'只會讀*一個數字*,所以你必須使用不同的方法 –
請參閱[這篇文章](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using -next-nextint-or-other-nextfoo)知道爲什麼你當前的代碼不能按預期工作 –