【问题标题】:code keeps going in an infinite loop when user puts in wrong value [duplicate]当用户输入错误的值时,代码会一直处于无限循环中[重复]
【发布时间】:2015-06-23 17:15:32
【问题描述】:

我添加了一个 while 循环,以便如果用户输入无效值,代码将重新提示用户输入有效值。但是当用户输入无效值时,代码会进入无限循环。任何帮助将不胜感激!

public static void main(String[] args) {
    System.out.println("Usage : enter a, b, & c from a quadratic equation");
    System.out.println("        aX^2 +bX + c = 0");
    System.out.println("        Result will be 2 values for X");

    Scanner in = new Scanner(System.in);
    double a = 0;
    double b = 0;
    double c = 0;
    double x1 = 0 ;
    double x2 = 0;
    double discriminant = 0;

    System.out.println("Please enter values for a , b, and c ");

    while(true){
        try
        {
            a = in.nextDouble();
            break;
        }
        catch(java.util.InputMismatchException E)
        {
            System.out.println("wrong input, try again");

        }
    }
    while(true){
        try
        {
            b = in.nextDouble();
            break;
        }
        catch(java.util.InputMismatchException E)
        {

            System.out.println("wrong input, try again");
        }
    }
    while(true){
        try
        {
            c = in.nextDouble();
            break;
        }
        catch(java.util.InputMismatchException E)
        {

            System.out.println("wrong input, try again");
        }
    }
    //x1 = (-b+sqrt(b*b - 4ac))/2a
    //x2 = (-b+sqrt(b*b - 4ac))/2a

    discriminant = b*b -4.0 * a * c;
    x1 = (-b + Math.sqrt(discriminant))/2.0*a;
    x2 = (-b - Math.sqrt(discriminant))/2.0*a;

    System.out.println("The two values for X are " + x1 + " and "  + x2);
}

【问题讨论】:

    标签: java loops while-loop


    【解决方案1】:

    the nextDouble method 抛出InputMismatchException 时,它不会消耗导致异常的错误输入。

    如果下一个标记无法转换为有效的双精度值,此方法将抛出 InputMismatchException。如果翻译成功,扫描仪会超过匹配的输入。

    您应该超越错误输入,否则nextDouble 将继续一遍又一遍地读取相同的错误输入。

    使用错误的输入并用in.next() 丢弃它,例如:

    catch(java.util.InputMismatchException E)
    {
        in.next();
        System.out.println("wrong input, try again");
    }
    

    【讨论】:

      【解决方案2】:

      以上建议可行。但是,您需要检查判别式。当判别式小于零时,您没有处理这种情况。如果判别式为负,您将得到 NaN 作为根。有关详细信息,请参阅 Math.sqrt() 文档。

      //x1 = (-b+sqrt(b*b - 4ac))/2a
      //x2 = (-b+sqrt(b*b - 4ac))/2a
      
      discriminant = b*b -4.0 * a * c;
      x1 = (-b + Math.sqrt(discriminant))/2.0*a;
      x2 = (-b - Math.sqrt(discriminant))/2.0*a;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多