I am try to catch an exception and get it to repeat, but it just creates an endless loop and then crashes the program... why is it doing this? Is it something wrong with my catch?
I have looked around the web and stackoverflow and can only find answers that don't related to what I am trying to achieve.
boolean bError = true;
System.out.println("How many players");
do
{
try
{
PLAYERS = input.nextInt();
if(PLAYERS > 5)
{
System.out.println("maximum of 5");
}//if
else
{
bError = false;
}
}
catch(InputMismatchException e)
{
System.out.println(e);
bError = true;
}
}while(bError && PLAYERS > 5);
It goes into an endless loop if you enter an invalid number because the invalid token is still left on the stream, and nextInt()
keeps trying over and over again to grab it.
You will have to get the data off the stream.
One thing you could do is use nextLine()
instead, then explicitly try and parse the returned String
into an integer (e.g. with Integer.parseInt()
).
Another thing you could do is call input.next()
(or input.nextLine()
) in the exception handler, to read (and discard) the garbage input. You may have to tweak the Scanner
delimiters to get next()
to work for you if it's not meeting your requirements with default settings.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다