gpt4 book ai didi

java - TicTacToe 数组越界

转载 作者:行者123 更新时间:2023-12-02 01:10:59 24 4
gpt4 key购买 nike

嘿,我正在制作一个 TicTacToe 游戏,它检查每个索引的值“x”或“o”,并且它一直给我错误 java.lang.ArrayIndexOutOfBoundsException: 3 第一个 if 语句。有什么帮助可以说明为什么会发生这种情况吗?

public boolean checkRowsForWin(int usrBrd, int WinSeq) {
int countX = 0;
int countO = 0;

for(int i = 0; i < usrBrd; i++) {
for(int j = 0; i< usrBrd; j++) {
if(board[i][j] == 'x') {
countX++;
}
else if(board[i][j] == 'o') {
countO++;
}
else {
countX = 0;
countO = 0;
}
if (countX >= WinSeq) {
return true;
}
else if (countO >= WinSeq) {
return true;
}
}
}
return false;
}

这是我初始化板的地方

    Scanner scnr = new Scanner (System.in);

System.out.println("Tic-Tac-Toe!");
System.out.println("How large would you like the board?(Must be greater
than 3)");
int usrBrd = scnr.nextInt();
if(usrBrd < 3) {
System.out.println("Not a valid number, please try again");
usrBrd = scnr.nextInt();
}
TicTacToe game = new TicTacToe(usrBrd);
game.initializeBoard(usrBrd);
System.out.println("What should the win sequence be? Write in form of
amount i.e \"3\" ");
int winSeq = scnr.nextInt();

这里是初始化板子的方法

public TicTacToe(int usrBrd) {
board = new char[usrBrd][usrBrd];
currentPlayerMark = 'x';
initializeBoard(usrBrd);
}
public void initializeBoard(int usrBrd) {
//loop rows
for (int i = 0; i < usrBrd; i++) {
//loop columns
for(int j = 0; j < usrBrd; j++) {
board[i][j] = '-';
}
}
}

最佳答案

你的错误出现在第二个for循环中

for(int j = 0; i< usrBrd; j++)

您总是检查 i < usrBrd 是否始终评估为 true,因为“i”永远不会在该 for 循环中递增。

关于java - TicTacToe 数组越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59414575/

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