Java 中的无限 While 循环

发布于 2024-08-23 14:56:43 字数 1396 浏览 5 评论 0原文

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

感谢您的帮助!

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;
              }
          }
      }
  }

Hey there! I'm trying to do some data input validation but I haven't been able to figure it out. I'm getting an infinite while loop in when I try to validate if the first character entered is a letter. . . .

Thanks for your help!

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;
              }
          }
      }
  }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

木格 2024-08-30 14:56:43

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

您可以重构代码,仅在出现错误时请求新输入。因此,在“错误...”系统输出之后,

额外:
我实际上会采取不同的做法。开头的“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;
    }
  }
}

You don't have an input = keyboard.nextLine(); in your second while loop.

You could refactor your code to only ask for new input when there is an error. So right after the sysout of 'ERROR...'

Extra:
I would actually do this different. The 'error = true' at the beginning is a bit confusing, because there might not be an error.

You could for example write a method called tryProcessLine, which reads the input and returns true if ok and false if there was an error, and than just do something like while(!tryProcessLine()){ }

Working example below:

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;
    }
  }
}
紅太極 2024-08-30 14:56:43

问题出在这一部分:

                        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 将抛出 NumberFormatException - 您需要捕获并处理它。

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

The problem is in this section:

                        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;
                            }
                        }

Once you have a letter in the first position, this loop can never terminate. It checks whether a letter is in the first position (it is), prints it, and repeats. Try changing to:

                            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;

                                    ...

Also, a couple of other things:

while (error == true) can be shortened to while(error).

Also, Integer.parseInt will throw a NumberFormatException if the input is not an integer - you need to catch and handle this.

Also, why do you need the second loop at all? It seems like it is only supposed to validate the input - if so, you can move this logic into the first loop and eliminate the second one. Only use loops for things that should happen repeatedly (like the user entering input data). There is no need to check the same input repeatedly.

天暗了我发光 2024-08-30 14:56:43

发生无限循环是因为第二个 while 循环重复检查字符串中的第一个字符 (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.");
}

The infinite loop occurs because the second while loop is repeatedly checking whether the first character in the String (input.charAt(0)) is a letter. Assuming that the result from this check is true the loop will never terminate.

Your code could be simplified to something like:

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.");
}
墨落画卷 2024-08-30 14:56:43

如果它是一个字符,则允许 error still = 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();

  }

}

If it is a character, you're allowing error to still = true, which is causing that loop to continue forever, you're not ever going back to the beginning and reading another line.

Here is some code that does what you want and is structured a little better.

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();

  }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文