扫描仪的.hasNextDouble()无法正常工作

时间:2017-10-09 19:30:58

标签: java

我一直在努力让这段代码按计划运行。 if(answer.hasNextDouble())未正确执行。这是代码:

//Variable for user input
String input = "";

//Creating a Scanner for keyboard
Scanner keyboard = new Scanner(System.in);

//...and for user's input
Scanner answer = new Scanner(input);

//Variable for validity check
boolean loanTerm_check = false;

int loanTerm = 0;

while (loanTerm_check != true) {
    try {
        System.out.print("\nEnter loan term in months       : ");
        input = keyboard.nextLine();
        loanTerm = Integer.parseInt(input);

        //Negative or null term exception
        if (loanTerm <= 0) {
            System.out.println("It is impossible to calculate payments for " +
                    "negative, null and fractional terms. Press Enter to retry.");
            keyboard.nextLine();
            input = "";
        } else {
            loanTerm_check = true;
            input = "";
        }
    } catch (NumberFormatException e) {
        if (answer.hasNextDouble()) {
            System.out.println("It is impossible to calculate payments for " +
                    "negative, null and fractional terms. Press Enter to retry.");
        } else {
            System.out.println("You did not enter a valid loan term. " +
                    "You entered: " + input + ". Press Enter to retry.");
        }
        keyboard.nextLine();
        input = "";
        continue;
    }
}

以下是样本运行:

Enter loan term in months       : 45.6
You did not enter a valid loan term. You entered: 45.6. Press Enter to retry.

我的想法是检查用户是否输入了double值并打印了一条提示重试的特定错误消息。

3 个答案:

答案 0 :(得分:3)

问题是当你声明

Scanner answer = new Scanner(input);

它将使用当前存储在input中的字符串(这是空字符串)。为input分配新值时,它不会更新answer正在扫描的文本。您希望使用用户输入的字符串,因此您应将answer的声明移到catch子句中。

或者,您可以尝试将input解析为double(使用Double.parseDouble(input))。如果抛出异常,则将其视为没有双精度,但如果成功,则input有一些解析为double但不是整数。

答案 1 :(得分:1)

问题是您是以String的形式从用户那里获取输入并将其存储在String类型变量input中,因此您没有double }。

input变量的数据类型更改为double,然后使用

进行用户输入

input = keyboard.nextDouble();

答案 2 :(得分:0)

您正在获取NumberFormatException,因为您没有将可解析的整数传递给parseInt

您需要更改

loanTerm = Integer.parseInt(input);

loanTerm = Double.parseDouble(input);