0

The issue is I have to validate proper input and the one I'm having issues with is validating only integer input (ex: if they enter a char or string, thats a problem). Well the issue is that if I run the program and on the first turn it works fine but after the first turn it prints out "Both inputs must be integers between 0 and 2." like 2 or 3 times then allows for re-entry. Also added the main method.

/**
 * Gets the position from the user of where the next move should be         
 * made. The board is then updated with a valid move
 *
 * @return true if there is a winner and false if there is no winner
 *
 */

public boolean getMove()
{

    boolean invalid = true;
    int row = 0;
    int column = 0;

    //keeps asking for a position until the user enters a valid one
    while (invalid)
    {

        row = -1;
        column = -1;

        System.out.println("Which row, column would you like to move to? Enter two numbers between 0-2 separated by a space to indicate position in (x,y).");

        if (keyboard.hasNextInt())
        {

            row = keyboard.nextInt();

            if (keyboard.hasNextInt())
            {

                column = keyboard.nextInt();

            }
        } else
        {

            keyboard.nextLine();
            System.out.println("\nBoth inputs must be integers between 0 and 2.\n");

        }
        //check that the position is within bounds
        if (row >= 0 && row <= 2 && column >= 0 && column <= 2)
        {

            //check that the position is not already occupied
            if (board[row][column] != ' ')
            {
                System.out.println("That position is already taken");
            } else
            {
                invalid = false;
            }
        } else
        {
            System.out.println("Invalid position");
        }
    }

    //if it's currently X's turn then mark the space as char 'X' else 'O'
    if (xTurn)
    {
        board[row][column] = 'X';

    } else
    {
        board[row][column] = 'O';

    }

    //fill in the game board with the valid position
    return winner(row, column);
}

1 Answers1

1

You problem is that the next int doesn't consider the new line character which goes in else part of you next run and is returned as blank.

To fix this problem you should use only Integer.parseInt(keyboard.nextLine()) in the entire code or read a keyboard.nextLine after ever keyboard.nextInt.

Related answer : https://stackoverflow.com/a/26089537/1085186

Community
  • 1
  • 1
StackFlowed
  • 6,575
  • 1
  • 26
  • 41