0

我试过搜索谷歌和几个这样的网站来找到我的问题的答案,但我没有任何运气。我在大学的第二级 Java 课程中,我试图弄清楚如何在使用 try-catch 块时对浮点数进行输入验证。该场景的要点如下:

驱动程序将调用方法promptForMotherHeight(),该方法应该将用户的条目作为浮点数拉入。问题在于,使用 try-catch 块时,如果扫描器检测到非浮点数,它不会将数据转储出扫描器的缓冲区。这会导致无限循环。I've tinkered with adding a Scanner.next() inside my catch block, but any data entered after the first attempt will not validate properly (meaning that I can enter in something such as 5.55555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555 and it will accept this as a valid input) .

这是我正在使用的代码(我已经在类的顶部导入了我需要的所有东西,而 MotherHeight 是类顶部的私有浮点实例变量):

public void promptForMotherHeight()
{    
    String motherHeightPrompt = "Enter mother's height in inches: ";
    String motherError1 = "Invalid entry. Must be positive.";
    String motherError2 = "Invalid entry. Must be a decimal number.";    
    boolean valid = false;

    do
    {
        System.out.print(motherHeightPrompt);
        try 
        {
            motherHeight = stdIn.nextFloat(); 
            valid = true;
        }
        catch (InputMismatchException e)
        {
            System.out.println(motherError2);
            stdIn.next();        
        }
    } while(!valid);
}

任何关于我如何完成正确输入验证的指针或提示将不胜感激。谢谢

4

1 回答 1

0

You could do the floating point number validation in the try-catch like this.

do {
    System.out.print(motherHeightPrompt);
    try {
        motherHeight = Float.parseFloat(stdIn.nextLine()); // This will read the line and try to parse it to a floating value
        valid = true;
    } catch (NumberFormatException e) { // if it was not a valid float, you'll get this exception
        System.out.println(motherError2);
            // You need not have that extra stdIn.next()
            // it loops again, prompting the user for another input
    }
} while (!valid); // The loop ends when a valid float is got from the user
于 2013-11-17T10:28:40.313 回答