Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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(;
        //Running the game cycle
        boolean flag=true;
        while (flag) {
            int action;
            System.out.println("Type your action please:");
            System.out.println("0: Exit app");
                action = sc.nextInt();

                switch (action) {
                    case 0:
                    case 1:

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

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 '14 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.

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

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.