Logan Serman
Logan Serman

Reputation: 29880

Easier way to guarantee integer input through Scanner?

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?

Upvotes: 1

Views: 14413

Answers (7)

Jason Carlson
Jason Carlson

Reputation: 11

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

Upvotes: 1

kevan1881
kevan1881

Reputation: 9

Example code:

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 the integer.

Upvotes: 0

goalaleo
goalaleo

Reputation: 21

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

Upvotes: 2

gizmo
gizmo

Reputation: 11909

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

Upvotes: 3

Joe Phillips
Joe Phillips

Reputation: 51120

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.

Upvotes: 0

Brandon DuRette
Brandon DuRette

Reputation: 4870

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

Upvotes: 0

Paul Tomblin
Paul Tomblin

Reputation: 182782

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

Upvotes: 4

Related Questions