【发布时间】:2013-02-21 15:09:19
【问题描述】:
我正在尝试写康威的人生游戏。现在我用加号表示活细胞,用负号表示死细胞。我的第一代看起来不错,然后出现越界错误。此外,我想在打印用户时为用户添加生成计数器。这是错误代码
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Life.Neighbors(Life.java:56)
at Life.nextGen(Life.java:35)
at Life.main(Life.java:18)
这是目前的代码
import java.util.Scanner;
public class Life {
public static boolean[][] gen(){
boolean[][] matrix = new boolean[10][10];
for(int i = 0; i < matrix.length; i++)
for(int j = 0; j < matrix.length; j++)
if( Math.random() > 0.7 )
matrix[i][j] = true;
return matrix;
}
public static void main(String[] args){
boolean[][] world = gen();
show(world);
System.out.println();
world = nextGen(world);
show(world);
Scanner s = new Scanner(System.in);
while(s.nextLine().length() == 0){
System.out.println();
world = nextGen(world);
show(world);
}
}
public static boolean[][] nextGen(boolean[][] world){
boolean[][] newWorld
= new boolean[world.length][world[0].length];
int num;
for(int i = 0; i < world.length; i++){
for(int j = 0; j < world[0].length; j++){
num = Neighbors(world, i, j);
if( occupiedNext(num, world[i][j]) )
newWorld[i][j] = true;
}
}
return newWorld;
}
public static boolean occupiedNext(int Neighbors, boolean occupied){
if( occupied && (Neighbors == 2 || Neighbors == 3))
return true;
else if (!occupied && Neighbors == 3)
return true;
else
return false;
}
public static int Neighbors(boolean[][] world, int row, int col) {
int num = world[row][col] ? -1 : 0;
for(int i = row - 1; i <= row + 1; i++)
for(int j = col - 1; j <= col + 1; j++)
if( inbounds(world, i, j) && world[i][j] )
num++;
return num;
}
public static boolean inbounds(boolean[][] world, int i, int j) {
return i >= 0 && i < world.length && j >= 0 &&
i < world[0].length;
}
public static void show(boolean[][] matrix){
String s = "";
for(boolean[] row : matrix){
for(boolean val : row)
if(val)
s += "+";
else
s += "-";
s += "\n";
}
System.out.println(s);
}
}
【问题讨论】:
-
请发布您遇到问题的特定代码部分。您在哪里看到
ArrayIndexOutOfBounds异常?您自己尝试了什么,以找出问题所在?另外,就您的第二个问题而言,您尝试了哪些解决方案? -
要求人们发现代码中的错误并不是特别有效。您应该使用调试器(或添加打印语句)来隔离问题,方法是跟踪程序的进度,并将其与您期望发生的情况进行比较。一旦两者发生分歧,你就发现了你的问题。 (然后如果有必要,你应该构造一个minimal test-case。)
-
在哪里你得到了异常?您希望我们只是猜测,或者创建一个项目并运行它,或者......?
-
另外,这是一个典型的家庭作业。您是否按照其他人的建议尝试过调试器。 SO 不仅是您在作业中遇到困难时的默认位置……您应该先自己尝试一下