2017-05-29 75 views
-3

首先,我很抱歉如果我正在複製郵件。我試圖尋找解決方案,並找不到它。我正在製作一個等級計算器,用戶通過掃描儀輸入雙倍「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); 

} 

我敢肯定我做了這個複雜得多,這一點也可以,但我想測試我的能力,使平均計算的方式我就沒有互聯網。希望我正確地格式化了這個。

感謝, 喬丹

+2

[驗證使用java.util.Scanner中輸入(https://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner) – Tom

+2

'nextInt的可能的複製()'只會讀*一個數字*,所以你必須使用不同的方法 –

+1

請參閱[這篇文章](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using -next-nextint-or-other-nextfoo)知道爲什麼你當前的代碼不能按預期工作 –

回答

1

您只需要一個Scanner,您可以使用String.startsWith而不是檢查集合。像,

double total = 0; 
int counter = 0; 
Scanner scan = new Scanner(System.in); 
System.out.println("Would you like to submit a number to calculate the average? [y/n]"); 
String userInput = scan.nextLine(); 
while (userInput.toLowerCase().startsWith("y")) { 
    System.out.println("Please input a number: "); 
    if (scan.hasNextInt()) { 
     total += scan.nextInt(); 
     counter++; 
    } 
    scan.nextLine(); 
    System.out.println("Would you like to submit another number to calculate the average? [y/n]"); 
    userInput = scan.nextLine(); 
} 
double average = total/counter; 
System.out.println("The average of those numbers is: " + average); 
+0

如果用戶輸入'yoo',將不會接受它! – Yahya

+0

@Yahya *「如果用戶輸入'Yoo'怎麼辦?」*該程序沒問題。 – Tom

+0

@Tom *「程序很好用」*,程序將執行'while-loop'程序段(即用戶輸入一個數字)。 – Yahya

1

我想你找什麼做的是這樣的。

try { 
    int input = scanner.nextInt(); 
    // remaining logic 
} catch (InputMismatchException e) { 
    System.out.println("uh oh"); 
} 

因此,如果用戶輸入一些東西,不能被解讀爲一個整數它會拋出一個InputMismatchException

您可以通過將其放入一個循環中來強制用戶輸入一個數字,然後再繼續。

相關問題