File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Problem with InputMismatchException in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with InputMismatchException in Java" Watch "Problem with InputMismatchException in Java" New topic
Author

Problem with InputMismatchException in Java

Gihan Madushanka
Ranch Hand

Joined: Apr 09, 2013
Posts: 71
Hello Guys !!!
Hope you are all doing good

Following code is intended to get an integer input from the user and displays it on the console. In any case if a user enters a bad input (Eg- string or char values) instead of an integer it throws an exception.



The program compiles and runs successfully. But my problem is Why should we use import.java.util.* for the above program.
Because import.java.util.Scanner is good enough for getting user inputs rather than importing the whole util package.
But here only using the Scanner class causes to not to compile the program successfully.
Can anybody explain me this situation ?
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14150
    
  18

Class InputMismatchException (yes, exceptions are also classes) is also in the package java.util. So only importing java.util.Scanner is not enough, you also have to import java.util.InputMismatchException. You do not need to import java.util.*.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Gihan Madushanka
Ranch Hand

Joined: Apr 09, 2013
Posts: 71
Jesper de Jong wrote:Class InputMismatchException (yes, exceptions are also classes) is also in the package java.util. So only importing java.util.Scanner is not enough, you also have to import java.util.InputMismatchException. You do not need to import java.util.*.

Thank you Jesper.
I have another question. Assume that a user entered a bad data.(Eg "rat"). It is not an integer. So that program throws an exception. I want that user to enter a number again.
How do I extend the above program to ask the user to enter a number again when he or she has already entered a bad input.
Thanks
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38851
    
  23
Gihan Madushanka,
Your post was moved to a new topic.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with InputMismatchException in Java