0

My objective is to make sure the user inputs an int. Else, exit the program. Then I do some coding that requires that int.

Code Snippet :

Scanner input = new Scanner(System.in);

    if (input.hasNextInt()) {
    //check if user enters an int

        int userinput = input.nextInt(); 
    // assign that int input to variable userinput

    // over 100+ lines of code using nextInt var "userinput" 

    } else {
    System.exit(1);
    // user did not enter an int
    }

Is there a better way to check for whether a user has entered an int and then use that int that doesn't require my entire program to be coded into that if-statement (because nextInt's scope is limited to that if-statement)?

It feels messy to me to put everything into one if-statement.

I wouldn't be allowed to use separate objects/classes since it's early in the semester for my class. This all goes in the main method, and I'm just using simple if-statements/scanner inputs.

Thanks

Janmenjaya
  • 4,030
  • 1
  • 19
  • 39
  • this could help http://stackoverflow.com/questions/3059333/validating-input-using-java-util-scanner – Dev. Joel Sep 21 '16 at 05:00
  • Have you tried declaring`int userInput` outside of the if statement? This way, you could use the `userInput` outside of that if statement. Also, you may want to brush up on variable scopes. – Hypnic Jerk Sep 21 '16 at 05:02
  • what about a `while` loop? `while(input.hasNextInt())` – Huntro Sep 21 '16 at 05:10
  • That seems fine to me. What makes you think it's ugly? – Joe C Sep 21 '16 at 05:13

2 Answers2

0

Here is a simple example of using hasNextInt () to validate a positive integer input

Scanner input = new Scanner(System.in);
int number;
do {
    System.out.println("Input Number ");
    while (!input.hasNextInt()) {
        System.out.println(" not a number!");
        input.next(); 
    }
    number = input.nextInt();
} while (number <= 0);
System.out.println("Númber válid " + number);
0

Definitely! Just negate the if statement and early exit:

Scanner input = new Scanner(System.in);

if (!input.hasNextInt()) {
    System.exit(1);
}

// "else"
doMagicalThings(input.nextInt());

Oh, I guess also to note: replace the 100 lines of code with a method call and break it up a bit. That'd be good to do in addition to the above.

Jameson
  • 5,452
  • 5
  • 26
  • 44