【问题标题】:Do while goes infinite with try catch用 try catch 做 while 无限期
【发布时间】:2016-09-17 07:36:26
【问题描述】:

尝试在 do while 循环中执行 try-catch 语句时遇到问题。我要求用户先输入字母,然后输入数字,如果他正确输入数字,程序结束。如果他输入字母而不是数字程序应该说“发生错误,请输入数字”并要求用户再次输入数字,但每次我输入字母而不是数字时,程序都会进入无限循环并且不允许我输入新值。 就这样 “发生错误,您必须输入数字” “请输入号码”。

public class OmaBrisem {

    public static void main(String[] args) {
        Scanner tastatura = new Scanner(System.in);
        boolean b = true;
        int a = 0;
        String r = "";
        System.out.println("Please enter a letter");
        r = tastatura.next();
        do {
            try {
                System.out.println("Please enter numerical value");
                a = tastatura.nextInt();
                b = true;
            } catch (Exception e) {
                System.out.println("An error occured you must enter number");
                b = false;
            }
        } while (!b);

    }

}

【问题讨论】:

    标签: java try-catch do-while infinite


    【解决方案1】:

    这是你的问题。如果用户在您期望数字的地方输入非数字,您的nextInt() 将引发异常,但它不会从输入流中删除字母!

    这意味着当您循环返回以再次获取号码时,该字母将仍然在那里,您的nextInt() 将再次引发异常。以此类推,无止境(或至少直到宇宙热死,或机器最终崩溃,以先到者为准)。

    解决此问题的一种方法是在nextInt() 失败时实际读取/跳过下一个字符,以便将其从输入流中删除。基本上你可以用Scanner.findInLine(".") 做到这一点,直到Scanner.hasNextInt() 返回true。

    以下代码显示了一种方法:

    import java.util.Scanner;
    public class MyTestProg {
         public static void main(String [] args) {
             Scanner inputScanner = new Scanner(System.in);
             System.out.print("Enter letter, number: ");
    
             // Get character, handling newlines as needed
    
             String str = inputScanner.findInLine(".");
             while (str == null) {
                 str = inputScanner.nextLine();
                 str = inputScanner.findInLine(".");
             }
    
             // Skip characters (incl. newline) until int available.
    
             while (! inputScanner.hasNextInt()) {
                 String junk = inputScanner.findInLine(".");
                 if (junk == null) {
                     junk = inputScanner.nextLine();
                 }
                 System.out.println("Ignoring '" + junk + "'");
             }
    
             // Get integer and print both.
    
             int num = inputScanner.nextInt();
             System.out.println("Got '" + str + "' and " + num);
         }
    }
    

    下面的文字记录显示了它的实际效果:

    Enter letter, number: Abcde42
    Ignoring 'b'
    Ignoring 'c'
    Ignoring 'd'
    Ignoring 'e'
    Got 'A' and 42
    

    【讨论】:

    • 我喜欢直到宇宙热死,或者机器最终坏掉,以先到者为准
    • 当您同时输入两个字母时,您的代码也会陷入无限循环
    • @HasS,是的,当有一个插入的换行符使findInLine 失败时。 - 我只测试了一行。虽然代码只是作为示例来说明这个概念,但我已经修复了更新。如果还有仍然有问题,请告诉我您正在使用的确切测试数据。
    • 您提供的解决方案完全可以,但是您正在做的只是在第一行仅使用单个字符,在第二行仅使用单个字符.. 我希望这对询问@paxdiablo 的家伙有所帮助
    【解决方案2】:

    只需在catch 块中添加tastatura.nextLine() 即可丢弃最后一个输入。

    【讨论】:

    • 这还不错,假设您很乐意丢弃该行的其余部分。我更喜欢更本地化的方法,但假设您清楚说明可能产生的影响,这也可以。
    【解决方案3】:

    当异常被捕获时,您可以通过break; 退出循环......所以只需添加:

                break;
    

    在你的 catch 块上 :)

    catch 子句如下所示:

    catch (Exception e) {
                System.out.println("An error occured you must enter number");
                b = false;
                break;
            }
    

    【讨论】:

      【解决方案4】:

      我意识到每当我插入错误的值并执行 while 循环时,我的程序都会忽略 try 块中的 Scanner 对象 tastatura,因此我创建了 Scanner 类的新对象并将其命名为 tastatura2,我的程序运行良好。

      Scanner tastatura = new Scanner(System.in);
              boolean b = true;
              int a = 0;
              String r = "";
              System.out.println("Please enter a letter");
              r = tastatura.next();
              do {
                  try {
                      Scanner tastatura2 = new Scanner(System.in);
                      System.out.println("Please enter numerical value");
                      a = tastatura2.nextInt();
                      b = true;
                  } catch (Exception e) {
                      System.out.println("An error occured you must enter number");
                      b = false;
                  }
              } while (!b);
      

      【讨论】:

      • 有时仅使用扫描仪进行输入会导致错误,这种情况发生在我身上很多次
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 2016-03-21
      • 1970-01-01
      • 2017-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多