【问题标题】:nextInt() having issues in a while loopnextInt() 在 while 循环中有问题
【发布时间】:2014-03-26 18:02:57
【问题描述】:

基本上我需要这个while循环执行4次

它将询问用户输入,然后在嵌套的 if 语句中使用该输入。 (重复4次)

第一个提示将出现,我可以输入一个输入。

但在那之后它只会给我一个错误。

并不断将错误指向“int userInput = scan.nextInt();”

我不知道它有什么问题。有人可以指导我吗?谢谢

    int count = 0;

    while (count < 4 ) {

        System.out.println(prompt1);
        int userInput = scan.nextInt();

        (some nested if statements here to do my task, they all have
         count++ at the end)

    }

【问题讨论】:

  • 你遇到了什么错误?你在哪里定义和初始化scan
  • 在while循环外初始化
  • 我们能看到那个代码吗?还要发布您收到的整个错误/异常。

标签: java while-loop java.util.scanner next


【解决方案1】:

你需要定义扫描

Scanner scan = new Scanner(System.in);

【讨论】:

    【解决方案2】:

    在请求它之前总是检查 nextInt 是否可用:

    if(scan.hasNextInt())
    {
     int userInput = scan.nextInt();
     // do something
    }
    

    【讨论】:

      猜你喜欢
      • 2014-12-21
      • 2015-05-23
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多