1

I know that this question has been answered countless times, and I have read an unreasonable amount of articles on this! However, I can just not figure it out and would love any input for this. I am making a tic tac toe game and in my main function, I am calling for the user to input which square to play in. Rather than just entering "3" and hitting enter, you have to press enter twice. Heres the code:

    int N = 0;
        while(true) {
            System.out.println("PLease choose a spot to place in (0 to quit): ");

            if(input.hasNextInt())
                {
                 N = input.nextInt();
                }
            else
                {

                input.nextLine();
                System.out.println("That wasn't a number, please enter a number( 0 to quit)");
                //continue;
                }

            if(N < 0 || N > 9)
                {
                System.out.println("That's not a valid choice, please pick another!");
                //continue;
                }
            if (N != 0)
                {
                Person.BoardUpdater(N,Game.GameBoard, "O");     
                Comp.AI(Game.GameBoard, "O" , "X");
                Game.draw(Game.GameBoard);

                }
            else
                {
                break;
                }


        }
Gilbert22
  • 47
  • 6
  • So what happens when you don't hit enter twice? Or are you looking for a solution which would require user to hit enter twice and aren't getting it? – M. Prokhorov May 20 '20 at 19:27
  • If I hit it twice it moves on with the program, I'm looking to be able to only hit enter once – Gilbert22 May 20 '20 at 19:31
  • According to most Java coding conventions, variables and methods begin with a lower case letter. Classes typically use an upper case letter. – NomadMaker May 20 '20 at 19:51

1 Answers1

1

I'm not 100% sure about this, but just try it and see if it works.

if(input.hasNextInt())
 {
  N = input.nextInt();
 }
else
    {
     // ...

You use hasNextInt() and then nextLine(). The scanner is seeing nextInt(), and judging if the next line has an int. Then, nextLine() goes to the next line after that, and reads that line. You can fix this with a single call of nextLine(), then use Integer.parseInt() to convert to a number. If you want to check if it is valid here is a good place to look: How to check if a String is numeric in Java. But if you want to see the basic answer, you have this method:

try {
    Integer.parseInt(s); // where s is a String
    return true;
} catch(NumberFormatException e) {
    return false;
}

Of course this is a slow way, but it's the easiest.

Higigig
  • 1,175
  • 1
  • 13
  • 25