[英]Error message prints twice the first time through
我正在使用以下代碼詢問用戶的身高(以英尺和英寸為單位),如果用戶的輸入不是整數,則返回錯誤消息:
loop = true;
while(loop){
if(input.hasNextInt()){
feet = input.nextInt();
loop = false;
break;
}
else{
System.out.println("Invalid input, please enter an integer.");
System.out.print("Feet: ");
input.nextLine();
}
}
loop = true;
System.out.print("Inches: ");
while(loop){
if(input.hasNextInt()){
inches = input.nextInt();
loop = false;
break;
}
if(!input.hasNextInt()){
System.out.println("Invalid input, please enter an integer.");
System.out.print("Inches: ");
input.nextLine();
}
}
程序返回錯誤消息,提示腳完全正常:
Feet: f
Invalid input, please enter an integer.
Feet:
但第一次返回錯誤消息(以英寸為單位)時,它將返回兩次:
Inches: f
Invalid input, please enter an integer.
Inches: Invalid input, please enter an integer.
Inches:
僅當用戶第一次輸入非整數的內容時,才會發生此錯誤。 我該如何擺脫呢?
如果用腳代替else
可以正常工作,為什么不再用英寸呢?
將if(!input.hasNextInt())
更改為else
應該可以解決該問題。
nextInt
方法不使用整數后的\\n
字符。
在第二個循環中,當hasNextInt
為false時,它將讀取一行。 該行將為空,因為它正在從最后一次讀取最后的\\n
。
在循環的第二次迭代中,它將讀取您輸入的最后一行,並再次出錯。
解決方法是始終使用nextLine()
並使用Integer.parseInt(String);
得到整數。 hasNextInt()
應該仍然可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.