簡體   English   中英

永遠不會結束用戶輸入的循環

[英]Never ending for loop with user input

我是 java 的新手,剛剛學會了如何使用用戶輸入。 我有一個 for 循環,它通過用戶輸入來詢問數字 10 次。 如果數字無效,它應該打印“無效數字”並且不計入增加的 for 循環。 相反,它只是永遠循環說“無效號碼”。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int sum = 0;
        Scanner scanner = new Scanner(System.in);
        for(int i = 1; i<=10; i++){
            System.out.println("Enter number #" + i + " ");
            boolean validInt = scanner.hasNextInt();
            if(validInt){
                int num = scanner.nextInt();
                sum += num;
            } else{
                System.out.println("Invalid Number");
                i--;
            }
        }
        System.out.println("Sum was " + sum);
        scanner.close();
    }
}

問題是您要在 2 個地方更新迭代器i

更好的方法是根據情況更新它。

我還建議您使用包裝類進行安全的 integer 轉換,並像在以下代碼中那樣正確處理異常:

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int sum = 0;
        Scanner scanner = new Scanner(System.in);
        for(int i = 1; i<=10; ){

            System.out.println("Enter number #" + i + " ");

            String input = scanner.nextLine();

            try{

                int num = Integer.parseInt(input);
                sum += num;

                i++; // If input is a valid integer, then only update i

            }catch(NumberFormatException e){

                System.out.println("Invalid Number");
            }
        }
        System.out.println("Sum was " + sum);
        scanner.close();
    }
}

我認為您也可以直接在 while 循環中使用 hasNextInt() 調整代碼。

while (scanner.hasNextInt()) { 
  int num = scanner.nextInt();
  sum += num;
}

我需要添加一個

scanner.nextLine();

在 if 和 else 語句之后清除掃描儀在這兩種情況下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM