views:

2131

answers:

5

For a program I am writing, I need to ask a user for an integer between 1 and 8. I've tried multiple (cleaner) ways of doing this but none of them worked, so I'm left with this:

    int x = 0;
    while (x < 1 || x > 8)
    {   
        System.out.print("Please enter integer  (1-8): ");

        try
        {
            x = Integer.parseInt(inputScanner.next());
        }
        catch(NumberFormatException e)
        {
            x = 0;
        }
    }

Where inputScanner is a Scanner. Surely there is a better way?

+3  A: 

Scanner does regular expressions, right? Why not check if it matches "^[1-8]$" first?

Paul Tomblin
+3  A: 

Using the nextInt() is already an improvement compare to simply using the next() method. And before that, you can use the hasNextInt() to avoid haing all this bunch of useless exceptions.

Resulting in something like this:

int x = 0;
do {
  System.out.print("Please...");
  if(scanner.hasNextInt()) x = scanner.nextInt();
  else scanner.next();
} while (x < 1 || x > 8);
gizmo
That results in an infinite loop if you provide a string.
Logan Serman
While I know your code is syntactically correct, having a if then on one line without braces is none standard. From Sun: Note: if statements always use braces {}. Avoid the following error-prone form: if (condition) statement; //AVOID! THIS OMITS THE BRACES {}!
WolfmanDragon
And he also omitted the semicolon after the while(), yet I somehow managed to understand his meaning. :)
Michael Myers
Oh my Gosh, yeah, this fucking semicolon! ;-)WolfmanDragon > Please get a life. Your comment make sens if you're in a big piece of code or in a somehow critical part of your code. Here, it's a simple snippet, a stupid SNIPPET.
gizmo
I thought a snip-it was one of those things the kids put around their ankle and jumped over while it spun in circles?
Joe Philllips
@Gizmo: I've heard that same reasoning thousands of times in my life. A lot of bugs have been introduced by that same reason. Although it is correct that such a small piece of code shouldn't be taken so serious, it ultimately reflects your practices. Is a matter of good habits.
OscarRyz
This site is about learning, it should not be about ego. When people point out errors that I make here, and I do make errors, I admit my mistakes and go on with life. It is much harder to break a bad habit than to a create a good habit from the start. Remember the original slogan for this site? ;)
WolfmanDragon
http://www.codinghorror.com/blog/archives/001169.html
WolfmanDragon
@Oscar > Ok, mister the medium. So, reading my snippet, did you deduce that, IRL, all my code is passed through a formatter at saving time? That I'm working using the TDD/BDD methodologies? That I introduced and guaranteed the good practices you're talking about in my company? I don't think so.
gizmo
A: 
String input;
int number;

while (inputScanner.hasNextLine())
{
    input = inputScanner.nextLine();

    if (input.equals("quit")) { System.exit(0); }
    else
    {
        //If you don't want to put your code in here, make an event handler
        //that gets called from this spot with the input passed in
        try
        {
            number = Integer.parseInt(input);
            if ((number < 1) || (number > 8))
            { System.out.print("Please choose 1-8: "); }
            else { /* Do stuff */ }
        }
        catch (NumberFormatException e) { number = 0; }
    }
}

I always like to pull in the full string so you can be sure that the user pushed the Enter button. If you just use inputScanner.nextInt() you can put two ints on a line and it will pull in one, then the other.

Joe Philllips
A: 

Apache Commons is your friend. See NumberUtils.toInt(String, int)

Brandon DuRette
Does it worth to bring a new lib just for one function? : - /
OscarRyz
A: 
int x;

Scanner in = new Scanner(System.in); System.out.println("Enter integer value: ); x = in.nextInt();

an array can also be used to store these integer.

kevan1881