gpt4 book ai didi

java - Java 中的 2D 数组 TicTacToe 游戏..验证问题

转载 作者:行者123 更新时间:2023-12-01 10:23:05 26 4
gpt4 key购买 nike

问题是我必须验证正确的输入,而我遇到的问题是仅验证整数输入(例如:如果他们输入字符或字符串,那就是一个问题)。问题是,如果我运行该程序,第一轮运行正常,但第一轮后它会打印出“两个输入都必须是 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);
}

最佳答案

您的问题是下一个 int 不考虑换行符,该换行符会进入您下次运行的其他部分并返回为空白。

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

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

关于java - Java 中的 2D 数组 TicTacToe 游戏..验证问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35466849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com