Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I'm pretty new here (as though to a game development).
So here's my question.
I'm trying to organize a really simple game cycle in my public static main() as follows:

Scanner sc = new Scanner(System.in);
        //Running the game cycle
        boolean flag=true;
        while (flag) {
            int action;
            System.out.println("Type your action please:");
            System.out.println("0: Exit app");
            try 
            {
                action = sc.nextInt();

                switch (action) {
                    case 0:
                        flag=false;
                        break;
                    case 1:

                        break;
                }
            }   catch (InputMismatchException ex) {
                    System.out.println(ex.getClass() + "\n" + "Please type a correct input\n");
                    //action = sc.nextInt();
                    continue;
             }

What's wrong with this cycle:
I want to catch an exception when user types text instead of number, show a message, warn the user, and then continue game cycle.

But instead of that, when users types wrong data, it goes into a eternal cycle without even prompting user.
What I did wrong?

share|improve this question

closed as off-topic by Josh Petrie Jan 10 at 16:28

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Programming questions that aren't specific to game development are off-topic here, but can be asked on Stack Overflow. A good rule of thumb is to ask yourself "would a professional game developer give me a better/different/more specific answer to this question than other programmers?"" – Josh Petrie
If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer 1

up vote 0 down vote accepted

Scanner's nextInt() skips over anything that not an int and returns the first int it finds so it doesn't trigger that exception.

See example near top of http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

What you want instead is to use next() which returns a String, and then check if this String is an integer or not.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.