【问题标题】:Why does this while loop work?为什么这个while循环有效?
【发布时间】:2013-10-23 21:39:33
【问题描述】:

为什么会这样:

Scanner keyboard = new Scanner(System.in);
int i;
int beerBottles = 100;

//Asks the user for the number of beer bottles on the wall
System.out.println("How many bottles of beer are on the wall?");

while (!keyboard.hasNextInt())
{
System.out.println("Make sure you enter an integer.");
keyboard.next();
}
//Sets beerBottles to the user entered value
beerBottles = keyboard.nextInt();

我在尝试确保用户输入是一个整数而不使用 try/catch 时偶然发现了这一点,我不知道它为什么会起作用,或者我是否遗漏了一些可怕的错误。它似乎工作得很好,这很好,但我不明白为什么“确保你输入一个整数”文本并不总是显示。谁能解释一下?

【问题讨论】:

    标签: java while-loop


    【解决方案1】:
    keyboard.hasNextInt()
    

    阻塞,直到它有输入要检查。当它找到一个整数值时,它返回true,否则返回false。

    因此,如果您输入一个整数值,则永远不会进入while 循环。如果你没有这样做,循环内的keyboard.next() 会清除你输入的值,让你再试一次。

    【讨论】:

      【解决方案2】:

      只要您不输入有效的整数值,Scanner.hasNextInt() 就不会返回 true。由于在 while 条件下检查 hasNextInt() 的否定 - 它打印“确保输入一个整数”。直到输入一个整数值。

      希望这会有所帮助 Scanner.hasNextInt()

      【讨论】:

      • 一个建议:我认为一些额外的信息会做出更好的回答......我认为只提供一个链接更适合发表评论
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 2017-04-18
      • 2018-03-17
      • 1970-01-01
      • 2020-01-17
      • 2016-07-27
      相关资源
      最近更新 更多