wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes What is wrong with this code? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "What is wrong with this code?" Watch "What is wrong with this code?" New topic
Author

What is wrong with this code?

Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707


I am not getting from this as I expect. Once exception comes, it is not
asking input from console. Only printing Line 1 consecutively, (remaining counts of outer loop)




Thanks,
cmbhatt


cmbhatt
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

In the catch block, you need to call nextLine() to skip the erroneous input.


[My Blog]
All roads lead to JavaRanch
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Satou,


In the catch block, you need to call nextLine() to skip the erroneous input.


That works fine, but question arises why so!
Please clarify!

Thanks,
cmbhatt
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Answer in the API :
nextInt():
An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix)

nextInt(radix):
This method will throw InputMismatchException if the next token cannot be translated into a valid int value as described below. If the translation is successful, the scanner advances past the input that matched


So you'll have to advance past the incorrect input if you want to continue scanning for an int.
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707

If the translation is successful, the scanner advances past the input that matched.


It means scan.nextInt(); fails to translate what is given to it, "a" will consist the previous value, just before succeeded input. That is correct
as I did so.

But how can be corelate this thing with what happened with my code?
and when I use nextLine() in the catch clause why doesn't it ask for input.
It means if previous nextInt() fails to translate, the further nextLine()
will only advance automatically, without asking input.???

Thanks,
cmbhatt
[ April 25, 2007: Message edited by: Chandra Bhatt ]
Kumar Sushil
Greenhorn

Joined: Jan 31, 2006
Posts: 29
its workin fine......no exception.
Kumar Sushil
Greenhorn

Joined: Jan 31, 2006
Posts: 29
its working fine......no exception.
Srinivasan thoyyeti
Ranch Hand

Joined: Feb 15, 2007
Posts: 557
Hi Chandra,

After adding Satou's nextLine now it working fine;
Here is code:


Here is the output:


Thanks & Regards, T.Srinivasan
SCWCD 1.4(89%), SCJP 5.0(75%)
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Thanks Satou and Srini,


Thanks and Regards,
cmbhatt
 
Consider Paul's rocket mass heater.
 
subject: What is wrong with this code?