0
我的Java片段存在小問題。我想採取一個雙或int並打印一個錯誤消息,並與任何其他輸入重新回來。現在,我對Java相當陌生,所以這可能不是實現這一目標的最有效方式,但您可以做什麼?Java,使用相同的輸入循環兩次
在任何情況下,我遇到的問題是,如果我輸入了無效的輸入,它打印我的錯誤消息兩次接受新的輸入之前。我只是使用sc.next()
,但如果用戶輸入帶空格的字符串,我不想接受另一個無效輸入。
,具有明顯的意見,因爲這是我的教授想要的東西,所以我做
這裏是我的代碼片段:
System.out.println("Enter hours worked: ");
while(hourFinisher == false)
{
//avoids type mismatch by allowing double or int to be entered
if(sc.hasNextDouble())
{
hours = sc.nextDouble();
isDouble = true;
hourFinisher = true;
}
else if(sc.hasNextInt())
{
intHours = sc.nextInt();
isDouble = false;
hourFinisher = true;
}
//in the case of a non-double or int, prints an error message and accepts a new input
else
{
System.out.println("Invalid Input! Please enter valid input.");
sc.nextLine();
}
要清楚,我所得到的,當我輸入,例如'a'
,兩次是Invalid Input! Please enter valid input.
。
我不想打印兩次;這是多餘的。任何指針都表示讚賞!
謝謝!其它輸入後
[掃描儀被使用next(),nextInt()或其它nextFoo後跳過nextLine()的可能的複製()methods](http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo) – azurefrog