我已经在这段代码上工作了几个小时,无法弄清这部分。该程序应该是一个井字游戏,当我不断收到此错误时,我在二维数组中出错了。我还可以使用有关如何使随机生成器查找特定行和列的帮助。
到目前为止是我的代码:
import java.util.Scanner;
import java.util.Random;
public class TicTacToe
{
public static void main (String[] args)
{
Scanner r = new Scanner (System.in);
int rows = 3;
int col = 3;
int [][] grid = new int [rows][col];
fillGrid(grid);
computerTurn(grid);
}//end main
public static void fillGrid(int [][] grids)
{
//int [][] grids = new int [3][3];
for (int r = 0; grids.length < 3; r++)
{
for(int c = 0; grids[r].length < 3; c++)
{
grids[r][c] = 0;
}
}
printGrid(grids);
}
public static void printGrid (int [][] x)
{
for (int i = 0; i < x.length; i++)
{
for (int y = 0; y < x[0].length; y++)
{
System.out.print (x[i][y] + "\t");
}
System.out.println();
}
}
public static void computerTurn (int [][] mygrid)
{
Random random = new Random();
int rows = 3;
int col = 3;
//int [][] grid = new int [rows][col];
//mygrid [rows][col] = random.nextInt(4);
for (int r = 0; r < 3; r++)
{
for (int c = 0; c < 3; c++)
{
//mygrid [rows][col] = random.nextInt(2);
if (mygrid [r][c] == 0)
{
//mygrid [r][c] = random.nextInt(3);
mygrid [rows][col] = 1;
}
/*if (mygrid [r][c] != 0)
{
//mygrid [rows][col] = random.nextInt(3);
mygrid [r][c] = 1;
}*/
}
}
printGrid(mygrid);
}
}
知道将indexOutOfBoundsException
投向哪一行会很有用。从异常末尾的: 3
,我们可以知道尽管someArr[3]
,但仍在数组中引用了代码someArr.length < 4
的某个位置。
您在fillGrid
中的嵌套循环上的终止条件有一些问题:
for (int r = 0; grids.length < 3; r++)
/* Loop never enters, because grids.lengh = 3 */
{
for(int c = 0; grids[r].length < 3; c++)
/* Loop also never enters, because grids[r].length = 3 */
{
grids[r][c] = 0;
}
}
我认为您的意思是拥有:
for (int r = 0; r < grids.length; r++)
{
for(int c = 0; c < grids[r].length; c++)
{
grids[r][c] = 0;
}
}
我还建议用这样的终止语句替换computerTurn
中的循环,因此该方法支持任何长度的数组。
关于您的异常,一旦找到发生的位置,请尝试打印您要访问的数组的长度,并打印您要访问的索引。通过这种方式,您可以继续调试为什么值错误。