2

Hi I'm currently developing a small booking program, I'm curios to know if i can use a Loop to run until a variable is equal to a specific type, notably a String or An Integer. For example i have the following below, and I want the user to always enter a number.

If not, am i right in presuming i should just develop a try/catch etc.?

Regards.

  public int SetHouseNo(){   
  System.out.println();        
  System.out.print("Please enter your house number:   ");    
  HouseNo=in.nextInt();
  return HouseNo; 
  }
Herten Ferford
  • 95
  • 2
  • 2
  • 11
  • `String` and `Integer` are not primitive types: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html – Bruno Mar 06 '12 at 21:41
  • Thank you, pretty basic stuff so thanks for clearing that up. – Herten Ferford Mar 06 '12 at 21:44
  • When you say "I want the user to always enter a number" is it (a) you want the user to enter the same specific number every time or (b) you want to make sure the user enters a number and not some other string? – Bruno Mar 06 '12 at 21:50
  • The user needs to always enter a number(Integer), and not say 'blah'. – Herten Ferford Mar 06 '12 at 21:51

6 Answers6

4

How to validate that the user entered an integer, without throwing or catching an exception:

Scanner sc = new Scanner(System.in);

while (!sc.hasNextInt()) { // <-- 'peeks' at, doesn't remove, the next token
    System.out.println("Please enter a number!");
    sc.next(); // <-- skips over an invalid token
}

return sc.nextInt();
Community
  • 1
  • 1
calebds
  • 23,502
  • 7
  • 39
  • 73
  • Thanks for that and the links, managed to adapt it to my code so now working perfectly, a really good way of doing it , need to wrap my head round precisely what's going on but works perfectly for what I'm doing. – Herten Ferford Mar 07 '12 at 12:14
3

Try/catch is overkill. This is a job for do/while.

int house;
do {
  house = in.nextInt();
while (house isn't right for whatever reason);
Louis Wasserman
  • 172,699
  • 23
  • 307
  • 375
3

Use this simple loop:

public static int askForInteger(Scanner in, String msg)
{
     while (true)
     {
         System.out.print(msg + " ");
         String input = in.next();
         if (input.matches("\\-?\d"))
             return Integer.parseInt(input);

         System.out.println("Sorry, you didn't enter a valid number.");
     }
}
Martijn Courteaux
  • 63,780
  • 43
  • 187
  • 279
1

Change 6 to your "specific" variable (Assuming HouseNo is a public variable and initialized toa value different than 6 before entering the method.):

public int SetHouseNo()
{   
  System.out.println();
  while(HouseNo != 6) 
  {   
    System.out.print("Please enter your house number:   "); 
    try
    {  
       HouseNo=in.nextInt();
    }
    catch(Exception e) { }
  } 
  return HouseNo; 
}
Juvanis
  • 25,000
  • 3
  • 61
  • 84
  • @HertenFerford time lag? what is it? – Juvanis Mar 06 '12 at 21:49
  • @HertenFerford hmm ok. i hope my answer was helpful. – Juvanis Mar 06 '12 at 21:52
  • Following the latest clarification in the question's comment, the question is more about checking a valid number (and not some other text) was entered, not that a specific number was entered. – Bruno Mar 06 '12 at 21:54
  • There will be an uncaught InputMismatchException if the token is not an int – calebds Mar 06 '12 at 21:57
  • @paislee method returns houseNo, so it has to be defined as integer. when it comes to user input, you are right and i have added handling all exceptions. – Juvanis Mar 06 '12 at 22:01
  • @HertenFerford i have edited my code so that it can handle exceptions, for example user may enter a string while you are excpeting an integer. if the 10 minutes is done tick accept please :) – Juvanis Mar 06 '12 at 22:07
1

You'll need to catch InputMismatchException from your reader if you want to allow numbers only. You could use a boolean to indicate whether you've found a suitable number or use auto boxing/unboxing and use a null value when no suitable value has been found:

Integer houseNumber = null;
do {
    try {
        System.out.print("Please enter your house number:");
        houseNumber = in.nextInt();
    } catch (InputMismatchException e) {
        houseNumber = null; // Not actually necessary, but perhaps clearer
    }
} while (houseNumber == null);
Bruno
  • 110,518
  • 24
  • 258
  • 357
1

Some people aren't agreeing with this, but here's what I would do:

public int SetHouseNo(){   
    System.out.println();        
    System.out.print("Please enter your house number:   ");    

    try
    {
        HouseNo=in.nextInt();
    }
    catch(NumberFormatException nfe)
    {
        System.out.println("Please enter a number...");
    }
    return HouseNo; 
}

And then somehow, possibly in the place where you call the method, make a while loop or something so it keeps asking until you entered a number. If you want, of course...

Daniel Bezden
  • 298
  • 3
  • 7
  • 19