I keep getting the error ArrayIndexOutOfBounds: 4 on line 21. The line is Spiral[VIndx][HIndx]=number. This program is supposed to create a spiral of numbers when given a certain dimension. For example, if given the dimension 3, a 3x3 2d array that spirals numbers. Here's what the spiral should be:
7 8 9
6 1 2
5 4 3
Why aren't my loops working?
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]);
}
}
}
}
First, your loop condition should use <
rather than <=
.
Second, if you think about the spiral you'll realize that you always end with a right movement. You hit the break
at the first time you have
if(number==endNumber)break;
but this doesn't exit you out of the while
loop - this only leaves the for
loop. So then you go into the down movement for
loop and get the index out of bounds exception.
Third, you need to first enter the center number before the loop.
Additionally, rightmovement
, leftmovement
, ... should all be increased by 2 each time. The reason for this is easier to see in a larger grid.
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
Notice the first right movement writes 2
, then the next one writes 8 9 10
, and the last one writes 22 23 24 25
and would have written 26
if you were to continue.
To fix the issue with break
not leaving the while
loop, just change it into a return
statement.