简体   繁体   English

发生错误时的无限循环

[英]Infinite loop when error occurs

When this code is run with a string as the input so that an error occurs it causes an infinite loop of the error message. 当使用字符串作为输入运行此代码时,如果发生错误,则会导致错误消息的无限循环。 I have tried inserting break; 我尝试插入中断; after the error message which does stop the loop but also stops the program. 错误消息之后,该消息确实会停止循环,但也会停止程序。 I would like it to loop back to the input request after an error occurs. 发生错误后,我希望它返回到输入请求。

import java.util.Scanner;

public class CubeUser                           
{                                               

    public static void main(String argv[])      
    {
        Scanner in = new Scanner(System.in);
        boolean error = true;
        System.out.print("Please input the length of the cube:");                               
        while(error == true)
        {
            if (in.hasNextDouble())
            {
                double length = in.nextDouble();
                Cube cube1 = new Cube(length);                                                          
                System.out.println("The surface area of cube1 is " + cube1.calculateSurfArea() );       
                System.out.println("The volume of cube1 is " + cube1.calculateVolume() );
                error = false;
            }
            else
            {
                System.out.println("Please enter a numerical value for the cube's length.");
            }
        }
        in.close(); 

    }  
}   

Move your scanner's cursor in case of error, otherwise it will keep reading the same value . 如果发生错误,请移动扫描仪的光标,否则它将继续读取相同的值。

else {
     System.out.println("Please enter a numerical value for the cube's length.");
     in.next();
}

Off note: Use if(error) instead of (error == true) . 注意:使用if(error)代替(error == true) Latter is bit frowned upon. 后来有些皱眉。

if (in.hasNextDouble())

This will fire the first time, when the user types it in. When there is an error though, it doesn't give the user a chance to type in a double value, hence the infinite loop. 这将在用户键入内容时第一次触发。但是,如果出现错误,则不会给用户输入double值的机会,因此将导致无限循环。

Restructure your loop like so: 像这样重组循环:

String input;
while((input = in.nextDouble()) != null)
{
    // Force the user to type a value.
    // The rest of your code here.
}

您必须阅读,输入,如果它不是一个双例如使用in.next()否则, in.nextDouble()当然会在接下来的迭代中真实的还有在“排队”非双值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM