• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with InputMismatchException in Java

 
Gihan Madushanka
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15459
42
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.*.
 
Gihan Madushanka
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49865
71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gihan Madushanka,
Your post was moved to a new topic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic