当前位置: 首页 > 知识库问答 >
问题:

无休止的循环-scanner.hasNextInt()在一个while循环中

易宏阔
2023-03-14

问题在代码的注释中,很抱歉,我认为它更整洁,因为流程很重要,我想。。。

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())

”hasNextInt

公共布尔值hasnetint()

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

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

共有1个答案

白通
2023-03-14

改为创建另一个扫描仪对象,忘记内部缓冲区中剩下的内容。

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);
    }
}
 类似资料:
  • 我的程序中有两个while循环。第一个是针对游戏菜单的,第二个是针对实际游戏的。如果“Gameover-Event”发生,我想返回菜单。我不知道该怎么做。

  • 只要给定条件为真,Perl编程语言中的while循环语句就会重复执行目标语句。 语法 (Syntax) Perl编程语言中while循环的语法是 - while(condition) { statement(s); } 这里的statement(s)可以是单个陈述或一个陈述块。 condition可以是任何表达。 当条件为真时,循环迭代。 当条件变为假时,程序控制将立即传递到循环之后的行。

  • 编写程序时,您可能会遇到需要反复执行操作的情况。 在这种情况下,您需要编写循环语句以减少行数。 JavaScript支持所有必要的循环,以减轻编程压力。 while循环 JavaScript中最基本的循环是while循环,将在本章中讨论。 while循环的目的是只要expression为真,就重复执行语句或代码块。 表达式变为false,循环终止。 流程图 while loop流程图如下 - 语法

  • 只要给定条件为真,Objective-C编程语言中的while循环语句就会重复执行目标语句。 语法 (Syntax) Objective-C编程语言中while循环的语法是 - while(condition) { statement(s); } 这里, statement(s)可以是单个语句或语句块。 condition可以是任何表达式,true是任何非零值。 当条件为真时,循环迭代。

  • While循环一次又一次地执行相同的代码,直到满足停止条件。 语法 (Syntax) 在R中创建while循环的基本语法是 - while (test_expression) { statement } 流程图 (Flow Diagram) 这里while循环的关键点是循环可能永远不会运行。 当测试条件并且结果为假时,将跳过循环体并且将执行while循环之后的第一个语句。 例子 (Exam

  • 在给定条件为真时重复语句或语句组。 它在执行循环体之前测试条件。 只要给定条件为真, while循环语句就会重复执行目标语句。 语法 (Syntax) 以下是while循环的语法。 while(condition){ statement(s); } 这里, statement(s)可以是单个语句或语句块。 condition可以是任何表达式,true是任何非零值。 当条件为真时,循环迭代。