I am writing a program that deals with a 2D array, does calculations based on surrounding elements and then creates a new array. To start I created a simple java program to test different cases. I want to correctly deal with if the element is on an edge of the array and if so set the "up, down, left, or right" equal to that element. My test program works for the element being on the top, left, or not on an edge, but not for the bottom or right. This is my current code:
public class ArrayTest
{
public static void buildE(int[][] array, int y, int x)
{
int up;
int down;
int left;
int right;
//if element is on the top left
if (y == 0 && x == 0)
{
up = array[y][x];
down = array[y + 1][x];
left = array[y][x];
right = array[y][x + 1];
}
//if element is on bottom right
else if (y == array.length && x == array.length)
{
up = array[y - 1][x];
down = array[y][x];
left = array[y][x - 1];
right = array[y][x];
}
//if element is on top right
else if(y == 0 && x == array.length)
{
up = array[y][x];
down = array[y + 1][x];
left = array[y][x - 1];
right = array[y][x];
}
//if element is on bottom left
else if (y == array.length && x == 0)
{
up = array[y - 1][x];
down = array[y][x];
left = array[y][x];
right = array[y][x + 1];
}
//if element is on top
else if (y == 0)
{
up = array[y][x];
down = array[y + 1][x];
left = array[y][x - 1];
right = array[y][x + 1];
}
//if element is on left
else if (x == 0)
{
up = array[y - 1][x];
down = array[y + 1][x];
left = array[y][x];
right = array[y][x + 1];
}
//if element is on bottom
else if(y == array.length)
{
up = array[y - 1][x];
down = array[y][x];
left = array[y][x - 1];
right = array[y][x + 1];
}
//if element is on right
else if (x == array.length)
{
up = array[y - 1][x];
down = array[y + 1][x];
left = array[y][x - 1];
right = array[y][x];
}
//if element is not on an edge
else
{
up = array[y - 1][x];
down = array[y + 1][x];
left = array[y][x - 1];
right = array[y][x + 1];
}
System.out.println();
System.out.print("#####################################");
System.out.println();
System.out.println("Array Element: " + array[y][x]);
System.out.println("Up: " + up);
System.out.println("Down: " + down);
System.out.println("Left: " + left);
System.out.println("Right: " + right);
}
public static void outputArray(int[][] array)
{
for(int row = 0; row < array.length; row ++)
{
for (int column = 0; column < array[row].length; column++)
System.out.printf("%d ", array[row][column]);
System.out.println();
}
}
public static void main(String[] args)
{
int [][] myArray = {{1, 12, 13, 14, 15}, {2, 22, 23, 24, 25},
{3, 32, 33, 34, 35}, {4, 42, 43, 44, 45}, {5, 52, 53, 54, 55}};
outputArray(myArray);
buildE(myArray, 4, 0);
}
}
Furthermore if I set y = 4 it does not recognize this as myArray.length. However I do not think this will be an issue in my actual program if I iterate through until array.length. Any help would be much appreciated!