![](/img/trans.png)
[英]Java Scanner hasNextDouble() doesn't work properly after the first instance
[英]Scanner's .hasNextDouble() doesn't work properly
我一直在努力使這部分代碼按計划工作。 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.
我的想法是檢查用戶是否輸入了雙精度值並打印一條特定的錯誤消息,提示重試。
問題是當您聲明
Scanner answer = new Scanner(input);
它將使用當前存儲在input
的字符串(這是空字符串)。 將新值分配給input
,它不會更新answer
正在掃描的文本。 您要使用用戶輸入的字符串,因此應將answer
聲明移到catch
子句中。
或者,您可以嘗試將input
解析為double
(使用Double.parseDouble(input)
)。 如果拋出異常,則將其視為沒有雙精度值,但如果成功,則input
具有解析為雙精度而不是整數的值。
問題是您將用戶的輸入作為String
並將其存儲在String
類型的變量input
因此,當然沒有double
。
將input
變量的數據類型更改為double
,然后使用
input = keyboard.nextDouble();
您正在獲取NumberFormatException,因為您沒有將可分析的整數傳遞給parseInt
你需要改變
loanTerm = Integer.parseInt(input);
至
loanTerm = Double.parseDouble(input);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.