I'm trying to catch InputMismatch exceptions and display a message that tells me where the exception occurred and what type of input is required. I need this to loop until the correct input is entered. I'm doing this by incrementing "statusCode
" and "expectedCode
" (which is what statusCode
has to be to exit the loop. expectedCode
increments before each loop, and statusCode
increments at the end of each method. I have my exception-related methods and data in a different class so that accessing it is easier later.
When I enter the correct input the first time (an int), it works as intended. However, if I enter incompatible data, I first get an extra blank input line, and then after input on that, my exception is caught. The problem is that all input afterwards throws the exception, no matter what I enter, and I can't proceed.
An ExceptionTracker
object called track
is declared prior.
Here is the relevant code:
track.incrementExpected(); //expectedCode=1
while(track.getStatusCode()!=track.getExpectedCode())
{
try
{
setGuests(); //statusCode=1 if successful
}
catch(InputMismatchException mis)
{
track.eventException();
}
}
the setGuests() method:
public void setGuests()
{
guests=0;
while(guests<5||guests>100)
{
System.out.print("How many guests will be attending? ");
guests=input.nextInt();
input.nextLine();
if(guests<5)
System.out.println("Events for fewer than 5 guests are not accepted.");
else
if(guests>100)
System.out.println("Events for greater than 100 guests are not accepted.");
}
if(guests>=CUTOFF)
PPG=BPPG;
else
PPG=SPPG;
price=guests*PPG;
track.incrementStatus(); //statusCode=1
}
in the ExceptionTracker class:
public void incrementExpected()
{
++expectedCode;
}
public void incrementStatus()
{
++statusCode;
}
public void eventException()
{
input.nextLine();
System.out.println("Error code: "+statusCode);
switch(statusCode)
{
case 3:
case 1:
System.out.println("Input must be of type int.");
break;
case 2:
case 0:
System.out.println("Input must be of type String.");
break;
}
}
Assistance is appreciated.
Edit: Stack trace is as follows
java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at Event.setGuests(Event.java:106)
at Event.<init>(Event.java:38)
It sounds like he did not discard your old input. Make sure it is reseted when the loop circle restarts.