【问题标题】:2D Arrays TicTacToe game in Java.. Validation issueJava 中的 2D Arrays TicTacToe 游戏.. 验证问题
【发布时间】:2016-02-17 20:15:39
【问题描述】:

问题是我必须验证正确的输入,而我遇到的问题是仅验证整数输入(例如:如果他们输入字符或字符串,那就是问题)。那么问题是,如果我运行程序并且在第一轮它工作正常,但在第一轮之后它会打印出“两个输入必须是 0 到 2 之间的整数”。像 2 或 3 次然后允许重新进入。还添加了main方法。

/**
 * 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);
}

【问题讨论】:

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


    【解决方案1】:

    你的问题是下一个 int 不考虑在你下一次运行的 else 部分中的换行符并返回为空白。

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

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

    【讨论】:

    • 啊,我明白了。这有帮助。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 1970-01-01
    相关资源
    最近更新 更多