• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Problem with InputMismatchException in Java

 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 74054
332
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Gihan Madushanka,
Your post was moved to a new topic.
reply
    Bookmark Topic Watch Topic
  • New Topic