问题在代码的注释中,对此感到抱歉,我认为这很整洁,因为流程很重要,我想...

import java.util.Scanner;

    public class ReadingUserInput {
        public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);
            System.out.println("Please, enter 10 numbers, for example, from 1 to 100!");

            int number = 0;
            int total = 0;
            int counter = 0;


            while (counter < 10) {
                System.out.println("Enter number #" + (counter + 1));

                boolean hasNextInt = scanner.hasNextInt(); // here we open the prompt for user to enter the value/s*
                                                           // internally, we are ready to check if the input is going to be int
                                                           // user types the value/s and clicks enter
                                                           // let's presume, he/she typed '3'
                                                           // internally, user's input is like that (if Windows**) - '3\n'
                                                           // because when user presses Enter - \n is added to what he/she typed

                if (hasNextInt) {                           // the app checks, ant it's int, that is, it's OK (true)

                    number = scanner.nextInt();            //here the application grabs user's input
                                                           //but, internally, it grabs only '3', because 'nextInt()' grabs only ints
                                                            // and doesn't "care" about the new feed/line - \n - character
                                                           // so, '\n' is left in Scanner's buffer!


                    counter++;

                    total += number;

                } else {
                    System.out.println("Invalid Input! Try again!");

                }
                //scanner.nextLine();                     // let's presume, this commented line, on the left of this line of comment, is absent in our code
                                                          // the flow of our code goes to boolean hasNextInt = scanner.hasNextInt();
                                                          // and again internally, we are ready to check if the input is going to be int
                                                          // and again the user is prompted (by a blinking cursor) to type his/her input
                                                          // and at this moment user types either a numeric again or a non-numeric character (a letter/letters)
                                                          // let's presume he/she is typing '4'
                                                          // and again, internally, user's input is actually like that (if Windows**) - '4\n'
                                                          // but scanner.hasNextInt() says 'OK', for the int is there! and it doesn't care about '\n'
                                                          //
                                                          // Now, let's presume that user (this time or next time) types 'a'
                                                          // Do we actually have 'a\n' ???
                                                          // and this time scanner.hasNextInt() says 'Alarm' - 'false'
                                                          // thus the input doesn't go to number = scanner.nextInt();
                                                          // So, does it mean that 'a\n' (or 'a') remains in Scanner's buffer???
                                                          // and it (scanner.hasNextInt()) kicks us to 'else'
                                                          // and we have an endless loop:
                                                             //Invalid Input! Try again!
                                                             //Enter number #...
                                                             //Invalid Input! Try again!
                                                             //Enter number #...
                                                             //Invalid Input! Try again!
                                                             //Enter number #...
                                                             //Invalid Input! Try again!
                                                             //Enter number #...
                                                             //Invalid Input! Try again!
                                                             //Enter number #...
                                                             //Invalid Input! Try again!
                                                             //Enter number #...
                                                             //Invalid Input! Try again!
                                                             //Enter number #...
                                                           //Why?
                                                            // Is there still 'a' (or 'a\n') and scanner.hasNextInt() throws the flow to 'else' endlessly,
                                                            // because "The scanner does not advance past any input"* ???
                                                            //
                                                            // or: there's only '\n', and again its not int, and we result in endless loop ???

                                                            // And finally, is that a different case? https://www.youtube.com/watch?v=_xqzmDyLWvs
                                                            // And PS: Is there anything wrong in my description in the comments?
// So what do we 'consume' by scanner.nextLine(); ???

                }
                scanner.close();
                System.out.println("Thank you, your total is " + total);
    }
}


// *来自Oracle:(https://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#hasNextInt%28%29

“具有NextInt

公共布尔hasNextInt()

如果可以使用nextInt()方法将此扫描器输入中的下一个标记解释为默认基数中的int值,则返回true。扫描仪不会前进超过任何输入。”

// ** https://knowledge.ni.com/KnowledgeArticleDetails?id=kA00Z0000019KZDSA2

最佳答案

而是创建另一个扫描程序对象,而忽略内部缓冲区中剩余的内容。

public class ReadingUserInput {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Please, enter 10 numbers, for example, from 1 to 100!");

        int number = 0;
        int total = 0;
        int counter = 0;

        while (counter < 10) {
            System.out.println("Enter number #" + (counter + 1));

            boolean hasNextInt = scanner.hasNextInt();

            if (hasNextInt) {
                number = scanner.nextInt();

                counter++;

                total += number;

            } else {
                System.out.println("Invalid Input! Try again!");
                scanner = new Scanner(System.in);
            }

        }
        scanner.close();
        System.out.println("Thank you, your total is " + total);
    }
}

关于java - 无休止的循环-while循环内的scanner.hasNextInt(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61742991/

10-09 13:48