mardi 20 septembre 2016

Is there another way to use hasNextInt() in Java without putting everything in the if-statement?

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

E.g.

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

Aucun commentaire:

Enregistrer un commentaire