【问题标题】:Can't get while loop to work, input twice?无法让while循环工作,输入两次?
【发布时间】:2012-11-21 17:02:52
【问题描述】:
import java.util.Scanner;
public class InputLoop
{
    public static void main(String[] args)
    {
        System.out.println("Enter an integer to continue or a non-integer to finish");
        Scanner scan = new Scanner(System.in);
        int input = scan.nextInt();
        while(scan.hasNextInt())
        {
            System.out.println("Enter an integer to continue or a non-integer to finish");
            scan.next();
        }


    }
}

这是我编写的第一个 while 循环,当它运行时,我必须输入一个数字两次才能继续打印“输入一个整数以继续.....” 感谢您的帮助!

【问题讨论】:

    标签: java loops while-loop


    【解决方案1】:

    根据文档 - Scanner#hasNextInt

    如果此扫描器输入中的下一个标记可以解释为 使用 nextInt() 方法在默认基数中的 int 值。扫描仪不 超越任何输入。

    【讨论】:

      【解决方案2】:

      这将是一个更好的 do ...while 循环。本质上是一样的,只是你完成后检查条件。

          do
          {
              System.out.println("Enter an integer to continue or a non-integer to finish");
              scan.next();
          } while(scan.hasNextInt());
      

      虽然如果你做了一段时间,你可以添加一个虚拟变量来确保你至少经历一次。

      Boolean firstTime=true;
      while(firstTime==true || scan.hasNextInt())
          {
              firstTime=true;
              System.out.println("Enter an integer to continue or a non-integer to finish");
              scan.next();
          };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-18
        • 1970-01-01
        • 1970-01-01
        • 2020-03-15
        • 2012-02-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多