当我建造我的乌拉姆(质数)螺旋时,我一直遇到这个奇怪的问题。我在SpiralMaker()中所做的是使用4步方法来创建螺旋。只要位置小于数组中的总方格数,并且它在第1步上,那么它应该向右移动1步并放置一个2。当它到达第2步时,它向上移动1并放置numLocation,现在是3。在第3步中,它向左移动两次,共2步,并将这些位置设置为4和5,等等。
但是当我运行这个时,我在第32行得到下面的异常,
线程"main"异常java.lang.ArrayIndexOutOfBoundsException: 5
import java.util.Arrays;
public class GridMaker {
private static int gridRow = 5; // R = length
private static int gridCol = 5; // C = height
private static int[][] grid = new int[gridRow][gridCol];
private static int totalSteps = (gridRow * gridCol); // total blocks on the grid
private static int numLocation = 1; // location refers to the number in the box, ie. 1, 2, 3, etc.
private static int rowLength = 1;
private static int colLength = 1;
public static void main(String[] args) {
grid[Calc.findArrayCenter(gridRow)][Calc.findArrayCenter(gridRow)] = 1;
spiralMaker();
for (int r = 0; r < gridRow; r++){
for (int c = 0; c < gridCol; c++){
System.out.print(grid[r][c] + " ");
}
System.out.println("");
}
}
private static void spiralMaker() {
for (int stepMaker = 0; stepMaker < 4; stepMaker++){//counter for the steps, only needs 1 of these
if (stepMaker == 1 && numLocation < totalSteps){
for (int r = 0; r < gridRow; r++){ //starts browsing array for the last number
for (int c = 0; c < gridCol; c++){
if(grid[r][c] == (numLocation - 0)){ //when it finds the last number
for(int i = 0; i < rowLength; i++){
grid[r][c + 1] = numLocation + 1; //when 0 no errors, when 1 "java.lang.ArrayIndexOutOfBoundsException"
}
numLocation++;
rowLength++;
}
}
}
}
}
}
}
// -----------------------
public class Calc {
public static int findArrayCenter(int center) {
int fcenter = 0;
if (center % 2 != 0)
fcenter = (int) ((center / 2));
else
fcenter = (center / 2);
return fcenter;
}
public static boolean isOdd(int num) {
boolean result = true;
if (num % 2 == 0)
result = false; // false = even, true = odd
return result;
}
public static boolean primeTester(int num) {
if (num == 1)
return false;
if (num % 2 == 0 && num != 2)
return false;
for (int primeCheck = 3; primeCheck <= num / 2; primeCheck += 2) {
if (num % primeCheck == 0 && num != primeCheck)
return false;
}
return true;
}
}
看起来您运行循环的迭代次数太多了。因为数组是[5][5],而你使用的是[r][c+1],所以你不希望c等于4。
改变for (int c = 0;c & lt;gridCol;c++) {
for (int c = 0;c & lt;gridCol-1;c++) {
,看看是否可以
请记住,Java中的数组是零索引的。
改变:
grid[r][c + 1] = numLocation + 1;
:
grid[r-1][c] = numLocation + 1;
您正在分配一个二维数组网格[gridRow][gridCol],它至少是一个5x5数组。在第29行中,您将从0数到gridCol(=4)。在第32行中,再次增加gridcol(或c)。因此,您正在索引数组的第6个元素,然而,该数组只有5个元素…