Recently, while doing my assignment and using the Scanner class, I stumbled upon an error that seem to be a bug with the said class. Read more to have your very own observation.
Attachments:
ScannerBug.java
The Program I attached above is supposed to check if the user is entering an invalid value for a supposed-to-be-integer input (which is actually just a segment of my program). If you check and read the src, you'd probably come up with the same conclusion, especially giving notion to the exception I used. I threw an InputMismatchException exception so that I would catch the scenery every time the faulty user inputs an invalid value. Take a look at the entire body of the program:
Scanner JInput=new Scanner(System.in);
int num=0;
boolean done=false;
while(!done)
{
try
{
System.out.print("Input Number: ");
num=JInput.nextInt();
done=true;
}
catch(InputMismatchException JExcept)
{
System.out.println("Enter a valid integer!");
}
}
As you can observe, the program is supposed to throw an InputMismatchException exception everytime the user inputs an invalid value to the integer variable num and then repeat the input process until the users gets to input correctly. Unfortunately, the program just continues to loop, printing Input Number: and then throw the InputMismatchException.
I read a few articles concerning this possible bug with the Scanner class and found out that some programmers have already encountered this situation (though mostly, their errors come up with the nextLine() method. Actually, I too had a lot of problems with that so I switched back to using BufferedReader). As for now, I won't be making any clear conclusion to this thing and will not clarify this a REAL bug to the Scanner class since it still not clarified. Anyway, I'll try to look for the real problem here and will post it here as soon as I catch something vital. Hope there would be a discussion of it somewhere...
Friday, July 9, 2010
Scanner Class bug?
Subscribe to:
Post Comments (Atom)
2 comments:
I got this bug fixed..
there's an article i read about that .
It will always loop because the
statement
num= JInput.nextInt();
will always scan or retrieve and processes what you have first entered.
therefore, the JInput must skip it and proceed to a newline..
by adding the JInput.nextLine();
at the catch statement
the problem will be solved.. :)
I got this bug fixed..
there's an article i read about that .
It will always loop because the
statement
num= JInput.nextInt();
will always scan or retrieve and processes what you have first entered.
therefore, the JInput must skip it and proceed to a newline..
by adding the JInput.nextLine();
at the catch statement
the problem will be solved.. :)
Post a Comment