gpt4 book ai didi

java - tictactoe 类的二维数组有问题

转载 作者:行者123 更新时间:2023-12-01 14:40:09 27 4
gpt4 key购买 nike

对于这个程序,我正在创建一个棋盘,它将成为我必须构建的井字棋游戏的基础。这将是一个非常简单的程序,仅使用 java 的基础知识。目前,我无法让 setX() 和 setO() 方法正常工作。这正是我用来构建我的两种方法的文本。

public void setX(int index) 和 public void setO(int index)如果索引在板和 BLANK 的范围内,则此方法应将 X 或 O 分配给板中适当的索引(setX 应该放置一个 X;setO 应该放置一个 O)。请记住TicTacToe 传递 1-9 范围内的数字,但棋盘中的索引比(在 0-8 范围内)。

我的具体问题是如何将“x”和“o”设置为正确的索引。当我运行单元测试文件(我使用的是 bluejay)时,使用这些方法的所有测试用例都会失败。它将返回该数组首先在元素 [0][2] 处不同(或 [1][1] 或我的数组中的任何组合);期望(或)但是是:

public class Board
{
// instance variables - replace the example below with your own
public int SIZE = 3;
private char BLANK = 'N';
private char [][] board;

/**
* Constructor for objects of class Board, intializes all elements to BLANK,
* creates board with SIZE elements
*/
public Board()
{
// initialise instance variables
board = new char[SIZE][SIZE];
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = BLANK;
}
}
}
/**
* this method returns the board
*/
public char [][] getBoard(){

return board;
}
/**
* prints the elements of the array board in a 3x3 grid
*/
public void display(){
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
System.out.print(board[i][j]);
}
}
}
/**
* This method assigns X to the appropriate index in board
*/
public void setX(int index){
index = index - 1;
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){

if((BLANK <= index) && (index <= board[i][j])){
board[i][j] = 'X';
}
}
}

}
/**
* This method assigns O to the appropriate index in board
*/
public void setO(int index){

for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){

if((BLANK <= index) && (index <= board[i][j])){
board[i][j] = 'O';
}
}
}
}
/**
* This method returns true if the index is not occupied by an X or O
*/
public boolean isAvailable(int index){
boolean available = false;
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board.length; j++){
board[i][j] = BLANK;
available = true;
}
}
return available;
}
}

最佳答案

首先,我想知道为什么你需要一个二维数组。为什么不将棋盘表示为九元素单数组?

除此之外,从 1-9 位置索引转换为适当的二维索引的方法是:

int i = (index - 1) / 3;
int j = (index - 1) % 3;

然后处理 board[i][j] 以获得一对索引。您的 setXsetO 方法不应循环。

关于java - tictactoe 类的二维数组有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16051131/

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