4

嘿!我正在尝试进行一些数据输入验证,但我无法弄清楚。当我尝试验证输入的第一个字符是否是字母时,我得到了一个无限循环。. . .

谢谢你的帮助!

public class methods
{
    public static void main(String args[]) throws IOException
    {
        String input ="";
        int qoh=0;
        boolean error=true;

        Scanner keyboard = new Scanner (System.in);

        //while (error)
        //{
            //error=true;

        while (error==true)
        {
           System.out.print("\nEnter Quantity on Hand: ");
           input = keyboard.nextLine();

           if (input.length() <1)
           {
               System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
               error=true;
               System.out.println(qoh);
               System.out.println(input);
            }
            else
            {
                error=false;
            }
        }

        error = true;

        while (error==true)
        {
            if (Character.isLetter(input.charAt(0)))
            {
                System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
                error=true;
                System.out.println(qoh);
                System.out.println(input);
             }
             else
             {
                 qoh = Integer.parseInt(input);
                 error=false;
              }
          }
      }
  }
4

4 回答 4

4

input = keyboard.nextLine();的第二个 while 循环中没有。

你可以重构你的代码,只在出现错误时才请求新的输入。所以就在“错误...”的系统输出之后

额外:我实际上会做不同的事情。开头的 'error = true' 有点令人困惑,因为可能没有错误。

例如,您可以编写一个名为 tryProcessLine 的方法,该方法读取输入并在正常时返回 true,如果出现错误则返回 false,而不仅仅是执行类似的操作while(!tryProcessLine()){ }

下面的工作示例:

import java.io.IOException;
import java.util.Scanner;

public class Methods {

  private static int qoh;

  public static void main(String args[]) throws IOException {

    while (!tryProcessLine()) {
        System.out.println("error... Trying again");
    }

    System.out.println("succeeded! Result: " + qoh);

  }

  public static boolean tryProcessLine() {

    String input = "";

    Scanner keyboard = new Scanner(System.in);

    System.out.print("\nEnter Quantity on Hand: ");

    input = keyboard.nextLine();

    try {
        qoh = Integer.valueOf(input);

        if (qoh < 0 || qoh > 500) {
          System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
          return false;
        } else {
          return true;
        }
    } catch (NumberFormatException e) {
        System.out.println("\n**ERROR06** - Quantity on hand must be numeric");
        return false;
    }
  }
}
于 2010-02-26T15:27:11.820 回答
1

发生无限循环是因为第二个 while 循环重复检查String ( input.charAt(0)) 中的第一个字符是否为字母。假设此检查的结果为真,则循环将永远不会终止。

您的代码可以简化为:

Integer qty = null;

while (scanner.hasNext() && qty == null) {
  String line = scanner.next();
  try {
    qty = Integer.parseInt(line);
  } catch(NumberFormatException ex) {
    System.err.println("Warning: Ignored non-integer value: " + line);
  }
}

if (qty == null) {
  System.err.println("Warning: No quantity specified.");
}
于 2010-02-26T15:29:10.657 回答
1

问题出在本节:

                        while (error==true)
                        {
                            if (Character.isLetter(input.charAt(0)))
                            {
                                System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
                                error=true;
                                System.out.println(qoh);
                                System.out.println(input);
                            }
                            else
                            {
                                qoh = Integer.parseInt(input);
                                error=false;
                            }
                        }

一旦你在第一个位置有一个字母,这个循环就永远不会终止。它检查一个字母是否在第一个位置(它是),打印它,然后重复。尝试更改为:

                            while (error==true)
                            {
                                if (Character.isLetter(input.charAt(0)))
                                {
                                    System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
                                    error=false;

                                    ...

此外,还有一些其他的事情:

while (error == true)可以缩短为while(error)

此外,如果输入不是整数,Integer.parseInt将抛出 a - 您需要捕获并处理它。NumberFormatException

另外,为什么你需要第二个循环呢?似乎它只应该验证输入 - 如果是这样,您可以将此逻辑移动到第一个循环并消除第二个循环。只对应该重复发生的事情使用循环(比如用户输入输入数据)。无需重复检查相同的输入。

于 2010-02-26T15:32:02.670 回答
0

如果它是一个字符,则您允许 error 仍然 = true,这将导致该循环永远继续,您永远不会回到开头并阅读另一行。

这里有一些代码可以做你想做的并且结构更好一些。

public class ScanInfo {

  Scanner keyboard = new Scanner(System.in);

  public ScanInfo(){
    String line = getLineFromConsole();
    while(null != line && !"quit".equals(line)){
      if(isValidInput(line)){
        int validNumber = Integer.parseInt(line);
        System.out.println("I recieved valid input: "+validNumber);
      }else{
        System.out.println("\n**ERROR06** - Quantity on hand must be between 0 and 500");
      }
      line = getLineFromConsole();
    }

  }

  private boolean isValidInput(String line){
    //basic sanity
    if(null == line || line.length() < 1){
      return false;
    }


    try {
      int number = Integer.parseInt(line);

      return (number >= 0 && number <= 500);

    } catch (NumberFormatException e) {
      return false;
    }

  }


  public static void main(String[] args) {
    new ScanInfo();

  }

  public String getLineFromConsole(){
    System.out.print("\nEnter Quantity on Hand: ");
    return keyboard.nextLine();

  }

}
于 2010-02-26T15:29:30.800 回答