二维数组Java中的TicTacToe游戏..验证问题

时间:2016-02-17 20:15:39

标签: java arrays java.util.scanner tic-tac-toe

问题是我必须验证正确的输入,而我遇到问题的只是验证整数输入(例如:如果他们输入字符或字符串,那就是问题)。好吧问题是,如果我运行程序并在第一个转弯它工作正常,但在第一个转弯后打印出"两个输入必须是0到2之间的整数。"喜欢2或3次然后允许重新进入。还添加了主要方法。

/**
 * 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 个答案:

答案 0 :(得分:1)

你的问题是,下一个int不会考虑下一次运行的其他部分的新行字符,并返回为空白。

要解决此问题,您应该在整个代码中仅使用Integer.parseInt(keyboard.nextLine())或者在keyboard.nextInt之后读取keyboard.nextLine。

相关答案:https://stackoverflow.com/a/26089537/1085186