Easier way to guarantee integer input through Scanner?

14,368

Solution 1

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

Solution 2

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);

Solution 3

I had to do a graphic interface calculator (works only with Integers), and the problem was, that the Tests didn't allow any Exceptions to be thrown if the input wasn't Integer. So I couldn't use

try { int x = Integer.parseInt(input)} catch (Exception e) {dosomethingelse}

Because Java programs generally treat an input to a JTextField as a String I used this:

if (input.matches("[1-9][0-9]*"){ // String.matches() returns boolean
   goodforyou
} else {
   dosomethingelse
}

// this checks if the input's (type String) character sequence matches
// the given parameter. The [1-9] means that the first char is a Digit
// between 1 and 9 (because the input should be an Integer can't be 0)
// the * after [0-9] means that after the first char there can be 0 - infinity
// characters between digits 0-9

hope this helps :)

Solution 4

You could try something like this:

Scanner cin = new Scanner(System.in);
int s = 0;    
boolean v = false;
while(!v){
    System.out.print("Input an integer >= 1: ");

    try {    
        s = cin.nextInt();
        if(s >= 1) v = true;
        else System.out.println("Please input an integer value >= 1.");
    } 
    catch(InputMismatchException e) {
        System.out.println("Caught: InputMismatchException -- Please input an integer value >= 1. ");
        cin.next();
    }
}
Share:
14,368
Logan Serman
Author by

Logan Serman

Updated on June 04, 2022

Comments

  • Logan Serman
    Logan Serman almost 2 years

    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?

  • Logan Serman
    Logan Serman over 15 years
    That results in an infinite loop if you provide a string.
  • WolfmanDragon
    WolfmanDragon over 15 years
    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 {}!
  • palantus
    palantus over 15 years
    And he also omitted the semicolon after the while(), yet I somehow managed to understand his meaning. :)
  • Joe Phillips
    Joe Phillips over 15 years
    I thought a snip-it was one of those things the kids put around their ankle and jumped over while it spun in circles?
  • OscarRyz
    OscarRyz over 15 years
    @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
    OscarRyz over 15 years
    Does it worth to bring a new lib just for one function? : - /
  • WolfmanDragon
    WolfmanDragon over 15 years
    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? ;)
  • gizmo
    gizmo over 15 years
    @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.