1
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

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.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged .