Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checking for integer, not string etc. 1

Status
Not open for further replies.

chris921

Technical User
Mar 9, 2004
82
GB
Hi,

Its just a small problem I'm having now with a program I've got.

I've got the input from the user (which is required to be an int) - how can I put my own error message on the screen if they enter a String etc?

Id just like to know if theres a simple and quick way around this?

Cheers,

Chris
 
Yes there is. Unfortunately, Java makes this pretty redundant if you have a lot of user prompts.

Code:
public static void promtUsr(){
  try
  {
    String s;
    System.out.print("Enter an integer: ");
    s = Integer.parseInt(keyIn.readLine());
  }
  catch(NumberFormatException e)
  {
    System.out.println("Please try again.");
    promtUser();
  }
}

-Bones
 
Oh dear, I must need more rest or something...
Change
String s
to
int s

Integer.parseInt obviously returns an integer. You also can modify my recursive method to return the integer too.

-Bones
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top