我不断收到错误 ArrayIndexOutOfBounds: 4 在第 21 行。该行是 Spiral[VIndx][HIndx]=number。该程序应该在给定特定维度时创建数字螺旋。例如,如果给定维度 3,则为螺旋数字的 3x3 二维数组。螺旋应该是这样的:
7 8 9
6 1 2
5 4 3
为什么我的循环不起作用?
import java.util.*;import java.io.*;
public class Spiral{
public static void Spiral(int dimensions, int [][] Spiral)
{
int endNumber = (int)Math.pow(dimensions, 2);
int number = 1;
int rightmovement = 1;
int downmovement = 1;
int leftmovement = 2;
int upmovement = 2;
int HIndx = (dimensions-1)/2;
int VIndx = (dimensions-1)/2;
while(number<=endNumber)
{
for(int i = 0;i<=rightmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
HIndx++;
if(number==endNumber)break;
}
rightmovement++;
for(int i = 0;i<=downmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
VIndx++;
if(number==endNumber)break;
}
downmovement++;
for(int i = 1;i<=leftmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
HIndx--;
if(number==endNumber)break;
}
leftmovement++;
for(int i = 1;i<=upmovement;i++)
{
Spiral[VIndx][HIndx]=number;
number++;
VIndx--;
if(number==endNumber)break;
}
upmovement++;
}
}
public static void main(String[]args)throws IOException
{
File file = new File("spiral.txt");
Scanner input = new Scanner(file);
String [] numbers = new String [2];
int i =0;
while (input.hasNextLine())
{
String line = input.nextLine();
numbers[i]=line;
i++;
}
int dimensions = 0;
input.close();
int [][] Spiral = new int [dimensions][dimensions];
dimensions = Integer.parseInt(numbers[0]);
int range = Integer.parseInt(numbers[1]);
if(dimensions%2==0)
{
dimensions+=1;
}
Spiral(dimensions, Spiral);
for(i = 0; i<dimensions;i++){
for(int j = 0; j<dimensions;j++){
System.out.println(Spiral[i][j]);
}
}
}
}