【问题标题】:While loop executing once before promptWhile 循环在提示之前执行一次
【发布时间】:2014-01-21 20:17:37
【问题描述】:

这是一个很难研究的问题,所以如果这是重复的,请原谅我。

基本上,我有一个 while 循环,只有当用户扫描的代码是整数时才会中断。我通过尝试Integer.parseInt(integer) 来检查这一点,并且仅在未引发 NumberFormatException 时才中断循环。

我的问题是,当循环第一次执行时,抛出异常,没有任何用户输入。

这是我的代码:

Scanner input = new Scanner(System.in);

while (true) 
{
    System.out.print("Please scan barcode: ");
    int inCode = 0;

    try
    {
        inCode = Integer.parseInt(input.next());
    }
    catch (NumberFormatException e)
    {
        System.out.println("Numbers only, please.");
    }

    if (inCode != 0) {
    // Do Stuff
    } else {
    System.out.println("Code can't be zero!");
    }
}

应该发生什么,是这样的:

请扫描条码:// And here they enter the barcode

但是却发生了这种情况:

请扫描条形码:请仅提供数字。
请扫描条形码:

编辑:

根据 Bohemian 的回答,我在代码中添加了 continue 关键字。这解决了问题,但只解决了一半。根据将我的问题搁置的人的要求(有充分的理由,正如我现在所看到的),我将为你们发布一个 SSCCE。不过,我将删除与数据库交互的方法,只保留有问题的路径:根据代码创建一个新帐户。

Scanner input = new Scanner(System.in);

while (true)
{
        System.out.print("Please scan barcode: ");
        int inCode = 0;

        try
        {
            inCode = Integer.parseInt(input.next());
        }
        catch (NumberFormatException e)
        {
            System.out.println("Numbers only, please.");
            continue;
        }

        if (true) // Here it checks if an account associated with the code entered exists in the database. Because I'm having issues when it creates a new account, I've made this true.
        {
            System.out.println("No account associated with that code! Create one?");
            System.out.print("(yes/no): ");
            String answer = input.next();
            if (answer.equalsIgnoreCase("yes"))
            {
                System.out.println("Alright.");
                System.out.print("Please enter a name: ");
                String name = input.next();
                System.out.print("Alright. Now I'll add that to the database... ");

                // Here I add that to the database. Omitted.

                System.out.println("Done! Please scan again to interface.");
            }
            else if (answer.equalsIgnoreCase("no"))
            {
                System.out.println("Okay then.");
            }
            else
            {
                System.out.println("Defaulting to no.");
            }
        }
}
// I still haven't written the code to interface with the account.

现在发生的事情是,它说(在第一次迭代中)

请扫描条码:

但是,在完成添加帐户的过程之后,它再次循环并说:

请扫描条形码:请仅提供数字。
请扫描条形码:

编辑:

请注意,所有内容都在while 循环内,因此当用户完成所有操作后,它会返回到:

请扫描条形码:

【问题讨论】:

  • 这段代码之前是什么?
  • 第一次执行while循环时,在try-catch部分之后System.out.println(inCode)给你什么输出?
  • 正如 Sotirios 所暗示的那样,问题很可能实际上不在此 sn-p 中。您能否发布所有代码,而不仅仅是您认为问题所在的部分?

标签: java loops input while-loop


【解决方案1】:

我想你想要的是这样的:

Scanner input = new Scanner(System.in);
while (true) {

    System.out.print("Please scan barcode: ");
    int inCode = 0;

    try {
        inCode = Integer.parseInt(input.next());
        if (inCode != 0) {
            // Do Stuff
            break;
        }
    } catch (NumberFormatException e) {
        System.out.println("Numbers only, please.");
    }
}

【讨论】:

  • 我认为每次迭代都创建一个新的扫描仪不是一个好主意
  • 老实说,当输入为int 时,这里没有理由使用Scanner.next()。另外,这并没有真的回答这个问题;他已经一个Scanner
【解决方案2】:

您的代码结构可以更好,这样既可以更清楚地了解正在发生的事情,也可以更轻松地跟踪问题。您只想循环输入数据 - 所以只需循环输入数据:

int inCode = 0;
while (true) {
    System.out.print("Please scan barcode: ");

    try {
        inCode = Integer.parseInt(input.next());
        break;
    } catch (NumberFormatException e) {
        System.out.println("Numbers only, please.");
    }
}

// Do stuff

您应该考虑使用scanner.hasNextInt()scanner.nextInt() 而不是scanner.next()。这也将避免使用这样的异常。通常使用异常来控制程序流程是一个坏主意——实际上它们应该用于处理异常情况。 Integer.parseInt 没有给你任何选择,但扫描仪可以。

【讨论】:

  • 嗯,任何输入都会打破循环,当输入预期为 int 时,没有理由使用 next()
【解决方案3】:

如果输入错误,我只会 continue 循环,那么你以后不需要测试它:

while (true) {
    System.out.print("Please scan barcode: ");
    int inCode = 0;

    try {
        inCode = Integer.parseInt(input.next());
    } catch (NumberFormatException e) {
        System.out.println("Numbers only, please.");
        continue; // ADDED THIS LINE
    }

    // Do Stuff with inCode
}

请注意,通过您的代码在输入后测试零,您可以排除零作为有效输入。此代码允许任何数字,包括零。小点,但不用担心边缘情况。

【讨论】:

    【解决方案4】:

    你可以试试这个

    String in=null;
    while (true) {
        System.out.print("Please scan barcode: ");
        int inCode = 0;
        try {
            in= input.next();
            inCode=Integer.parseInt(in);
        } catch (NumberFormatException e) {
            System.out.println("Numbers only, please.");
        }
    
    if (inCode != 0) {
    // Do Stuff
    } else {
    // Repeat loop
    }
    

    或者你可以直接通过 Scanner 对象读取一个整数,而不是使用Integer.parseInt() 方法。

    int inCode=0;
    while(true) {
      System.out.print("Please scan barcode : ");
      inCode=input.nextInt();
    
      if(inCode!=0){ //do stuff }
      else { //Repeat Loop }
     }
    

    【讨论】:

    • 我尝试过使用 nextInt,这说明了我的问题的核心:Please scan barcode: Exception in thread "main" java.util.InputMismatchException 在用户触摸条形码扫描仪之前,扫描仪对象中输入了一些内容。什么给了?
    【解决方案5】:

    编辑后,问题很明显:您的while (true) 循环中没有break 语句,因此它会一直循环下去。

    就个人而言,我建议您将大部分代码移出循环,并仅将条形码解析代码保留在其中,例如像这样:

    int inCode;
    while (true) {
        System.out.print("Please scan barcode: ");   
        try {
            inCode = Integer.parseInt(input.next());
            if (inCode == 0) {
                System.out.println("Code can't be zero!");
            } else {
                break;  // we got a valid barcode! end the loop and move on...
            }
        } catch (NumberFormatException e) {
            System.out.println("Numbers only, please.");
            // no need for a "continue" here, since the loop will restart anyway
        }
    }
    
    // rest of the code here...
    

    甚至可能:

    int inCode;
    while (true) {
        System.out.print("Please scan barcode: ");   
        try {
            inCode = Integer.parseInt(input.next());
        } catch (NumberFormatException e) {
            System.out.println("Numbers only, please.");
            continue;
        }
        if (inCode == 0) {
            System.out.println("Code can't be zero!");
            continue;
        }
        break;  // we have a valid barcode! end the loop and move on...
    }
    
    // rest of the code here...
    

    【讨论】:

    • 它应该永远循环。将它放在while 循环中的目的是,当用户完成接口时,它会返回到开头 (Please scan barcode: )。
    猜你喜欢
    • 2019-09-03
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2012-02-12
    相关资源
    最近更新 更多