我一直在努力让这段代码按计划运行。 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值并打印了一条提示重试的特定错误消息。
答案 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);