2D array and an out of bounds exception - java

The last for loop will compile but it won't run. It says that array index out of bounds exception:17. I just want to add a ColorRectangles (subclass of ColorShape) to the 1-8 columns in the 17'th row
private ColorShape[][] _tiles;
public GamePanel()
{
_tiles = new ColorShape[8][17];
for (int i = 0; i<16; i++){
for(int j=0; j<8;j++){
_tiles[j][i] = null;
}
}
for (int j=0; j<8;j++){
_tiles[j][17] = new ColorRectangle(Color.BLACK);
}
}

Your array size is 17. Arrays are zero-indexed. This means your maximum array index for your second dimension is actually 16, not 17.
Either change your reference to tiles to:
_tiles[j][16] = new ColorRectangle(Color.BLACK);
OR make your _tiles array bigger like so:
_tiles = new ColorShape[8][18];
Either will fix this problem.
May I also suggest that your game panel object accept 2 dimensions, width and height. This makes your class more useable should you decide to use it again, or change its dimensions. Avoid hardcoding values whenever appropriate. Here it would be most appropriate.
Here's a rewrite for you:
private ColorShape[][] _tiles;
public GamePanel(int width, int height)
{
_tiles = new ColorShape[width][height];
for (int i = 0; i<height; i++){
for(int j=0; j<width;j++){
_tiles[j][i] = null;
}
}
for (int j=0; j<width;j++){
_tiles[j][tiles[j].length-1] = new ColorRectangle(Color.BLACK);
}
}
And here's how you would use it in your case:
GamePanel panel = new GamePanel(8, 17);
But you can always easily change your panels dimensions now!
GamePanel panel = new GamePanel(100,100);
Nifty huh?

This:
_tiles[j][17] = new ColorRectangle(Color.BLACK);
17 is not a valid index for your array since you sized it as [8][17]. Indices are from 0...length - 1, so in your case, up to 16. This is because arrays in Java (and any reasonable programming language) are zero-indexed. Thus, replace with
_tiles[j][16] = new ColorRectangle(Color.BLACK);
and at least you won't get an ArrayIndexOutOfBoundsException.
I just want to add a ColorRectangles (subclass of ColorShape) to the 1-8 columns in the 17'th row
See, in a zero-based indexing scheme, the 17th row is the row with index 16.
The first row corresponds to that with index 0. The second row corresponds to that with index 1. Etc. In general, the nth row corresponds to that with index n - 1 and a row with index n is actually the (n + 1)th row (assuming 0 <= n < length - 1).

Your problem is here:
_tiles[j][17] = new ColorRectangle(Color.BLACK);
You should have this instead (note that arrays are zero-indexed, so 17th column is at index 16):
_tiles[j][16] = new ColorRectangle(Color.BLACK);

In java, indexing starts from zero (0);
private ColorShape[][] _tiles;
public GamePanel()
{
_tiles = new ColorShape[8][18]; // new dim is 18 so last index is 17
for (int i = 0; i<18; i++){
for(int j=0; j<8;j++){
_tiles[j][i] = null;
}
}
for (int j=0; j<8;j++){
_tiles[j][17] = new ColorRectangle(Color.BLACK); //17 was out of bounds
}
}

The length of your array is [8][17] but the indexes go from [0] to [16].
Therefor replace
_tiles[j][17] = new ColorRectangle(Color.BLACK);
with
_tiles[j][16] = new ColorRectangle(Color.BLACK);

You're declaring your array with 8 fields in x range and 17 fields in y range in your code:
_tiles = new ColorShape[8][17];
Because you start counting from zero in the IT, the range is from zero to sixteen (0-16).
So if you want the last field of the array, you have to use the field 16 (_tiles[j][16]).
The code should be:
_tiles[j][16] = new ColorRectangle(Color.BLACK);
The whole thing is called zero-based-numbering/index.

You might also have a bug for the first loop.
Instead of
for (int i = 0; i<16; i++)
it should be
for (int i = 0; i<17; i++)
Arrays are zero-indexed meaning the starting index is 0 up to length-1.
So, in your case, it is up to 16.
For your second loop, it should be
_tiles[j][16] = new ColorRectangle(Color.BLACK);

According to the JLS (Array Access) - All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1.
So if you initialize an array like you did _tiles = new ColorShape[8][17];. In order to access you need to do it by 0 to 7 and 0 to 16.
Now, with _tiles[j][17] = new ColorRectangle(Color.BLACK); you are trying to access something with is outside the array you have initialized and therefore you get java.lang.ArrayIndexOutOfBoundsException.

Related

Index out of Bounds?

Vertex [] vertices = new Vertex[n];
int [] numbers = new int[n*2];
AdjacencyList[] all = new AdjacencyList [n+1];
for (Vertex v : vertices)
{
System.out.println(v.value);
AdjacencyList a = new AdjacencyList(v);
for (int i = 0; i < n; i += 2)
{
if (numbers[i] == v.value){
a.connected[i] = vertices[i+1];//array index out of bounds exception:19
else { a.connected[i] = v; }
}
all[0] = a; //add the finished adjacency list to the array
}
with n = 19 can I'm getting an index out of bounds error at the point indicated in the code. I'm not sure where I'm going wrong, as everything is still within the bounds of 19
vertices = list of Vertex [1-19],
numbers is a flattened array of edges
In the line:
a.connected[i] = vertices[i+1];
You call the index i+1. This will result in an index out of bounds exception. (In your example of when n equals 19: The valid index's will be [0-18]. Your loop will go from 0-18. But in the line it will then add one to it. 18+1 = 19, which is an invalid index)
In your loop change the condition to:
for (int i = 0; i<n-1; i+=2){
To make sure it will not go out of bounds when you add one.
Your array has length, n=19, meaning index [0-18] and i is incremented by 2.
So when i = 18,
a.connected[i] = vertices[i+1];
tries to access vertices[19] which is not existent. Hence ArrayOutOfBoundException. Hope this helps.

Why do my loops stop early when iterating through and array

So I am trying to iterate through a 4 by 3 array of objects and set the value of each object according to user input, but I've run into a problem where the iteration through the array stop at 6 instead of the total 12. I've tried a few way of writing the iterators but they always fail. This is the code.
Card[][] field = new Card[3][2];
void setvals(){
Scanner scanner = new Scanner(System.in);
for(int row= 0; row < field.length; row++){
for(int col = 0; col < field[row].length; col++) {
String input = scanner.nextLine();
field[row][col] = new Card();
field[row][col].makeCard(input);
}
}
}
I have also tried <= instead of < but then it gives me array index out of bounds. I have no clue what the problem is.
Your problem is with the array:
Card[][] field = new Card[3][2];
You want the array to be 4 x 3, then set the dimensions as so:
Card[][] field = new Card[4][3];
The reason your code is not working, is since you currently have a 2 x 3 array, evaluating to 6 iterations. A 4 x 3 array would evaluate to 12 iterations, as you want.
You say:
So I am trying to iterate through a 4 by 3 array of objects...
And here is your array: Card[][] field = new Card[3][2];.
That is not a 4x3 array. It is a 3x2 array, which means there should be 6 iterations in your loop, which is what is happening. There is no error here.

Arrays in array, 100 rows, dynamic columns

I'm trying to get this:
arrays[1][0] = 5
arrays[2][0] = 7
arrays[2][1] = 2
arrays[3][0] = 6
arrays[3][1] = 9
arrays[3][2] = 11
So I want arrays[1][] to have one element of random data, arrays[2][] to have 2 elements of random data and so on until I have 100 arrays. So my last array would be arrays[100][] with 100 elements of random data.
This is the code I have now but I get a NullPointerException when arrays[i][j] = generator.nextInt(max) is executed:
Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
for (int j=0; j <= i-1; j++){
arrays[i][j] = generator.nextInt(max);
}
}
Your
Comparable[][] arrays = new Comparable[100][];
line only creates the outermost array. You need to create the arrays that go in it, e.g. something like this:
Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
arrays[i] = new Comparable[/* relevant length here*/]; // <====
for (int j=0; j <= i-1; j++){
arrays[i][j] = generator.nextInt(max);
}
}
It's unclear to me why you start i at 1 or where the randomness should be (I'm guessing at /* relevant length here */), but hopefully that points you the right way.

Adding each value to an integer array

Can you help me with my problem? I need to add values to my int array but all I get is an ArrayIndexOutOfBoundsException.
public static void numberSort(){
int quantity = 0;
int[] values = new int[quantity];
int allocate = 0;
quantity = Integer.parseInt(JOptionPane.showInputDialog("How many values do you wish to sort? : "));
for(int x = 0; x <= values.length; x++){
allocate = Integer.parseInt(JOptionPane.showInputDialog("Values you want to sort : "));
values[allocate] = x;
System.out.println(values[x]);
}
int quantity = 0;
int[] values = new int[quantity];
You're allocating an array with 0 locations, which is effectively a zero-length array. This means that it really doesn't have any valid locations, so you can't store anything into it. This is why you're getting an ArrayIndexOutOfBounds exception when you attempt to store anything inside the array.
You will have to move the line where you allocate values to the line after the line where you read in the value of quantity.
Your next problem is your for loop:
for(int x = 0; x <= values.length; x++)
Array indices run from 0 to array.length - 1. So typically the terminating condition for the for loop is x < values.length. If this was your code, you wouldn't have seen this exception. However, even if you fix this to make quantity a non-zero value, you will get the exception when you attempt to fill the array since values[array.length] is out of bounds. So you will have to change your for loop to:
for(int x = 0; x < values.length; x++)
I also noticed that you have values[allocate] = x;. What you want is values[x] = allocate;, since you want the xth element of the array.
This line is your problem
int quantity = 0;
int[] values = new int[quantity];
You are creating an array with length 0. The length of an array is established when the array is created. After creation, its length is fixed.
Read more in tutorials: Arrays
For quick fix in your code just init your array after quantity
int quantity = Integer.parseInt(JOptionPane.showInputDialog("How many values do you wish to sort? : "));
int[] values = new int[quantity];
And in for loop change <= to < cause arrays starts in 0.
for(int x = 0; x < values.length; x++){
allocate = ...
values[x] = allocate; // you want to allocate in position "x" allocate
}
Aside from creating an array of 0 length, your for loop end condition is incorrect. You wrote x <= values.length, but you should write x < values.length. Since arrays in Java are 0-indexed, that means the valid range of indices are 0 to values.length - 1.
I count three errors in there. The most significant one:
for(int x = 0; x <= values.length; x++){
Java arrays index from zero - that means that for example an array with length of 5 has indexes 0, 1, 2, 3 and 4. Anything beyond that in either direction results in the ArrayIndexOutOfBoundsException. Because you use <=, you read one value beyond what's allowed. Replace it with <.
Also, you initialize your array to size zero. That means you can't really use it. Initialize your array with quantity only once quantity has the correct value!
Finally, I believe you want values[x] = allocate;, not vice versa.

Getting the length of two-dimensional array

How do I get the second dimension of an array if I don't know it? array.length gives only the first dimension.
For example, in
public class B {
public static void main(String [] main){
int [] [] nir = new int [2] [3];
System.out.println(nir.length);
}
}
See that code run live at Ideone.com.
2
How would I get the value of the second dimension of nir, which is 3?
which 3?
You've created a multi-dimentional array. nir is an array of int arrays; you've got two arrays of length three.
System.out.println(nir[0].length);
would give you the length of your first array.
Also worth noting is that you don't have to initialize a multi-dimensional array as you did, which means all the arrays don't have to be the same length (or exist at all).
int nir[][] = new int[5][];
nir[0] = new int[5];
nir[1] = new int[3];
System.out.println(nir[0].length); // 5
System.out.println(nir[1].length); // 3
System.out.println(nir[2].length); // Null pointer exception
In the latest version of JAVA this is how you do it:
nir.length //is the first dimension
nir[0].length //is the second dimension
You can do :
System.out.println(nir[0].length);
But be aware that there's no real two-dimensional array in Java. Each "first level" array contains another array. Each of these arrays can be of different sizes. nir[0].length isn't necessarily the same size as nir[1].length.
use
System.out.print( nir[0].length);
look at this for loop which print the content of the 2 dimension array
the second loop iterate over the column in each row
for(int row =0 ; row < ntr.length; ++row)
for(int column =0; column<ntr[row].length;++column)
System.out.print(ntr[row][column]);
int secondDimensionSize = nir[0].length;
Each element of the first dimension is actually another array with the length of the second dimension.
Here's a complete solution to how to enumerate elements in a jagged two-dimensional array (with 3 rows and 3 to 5 columns):
String row = "";
int[][] myArray = {{11, 12, 13}, {14, 15, 16, 17}, {18, 19, 20, 21, 22}};
for (int i=0; i<myArray.length; i++) {
row+="\n";
for (int j = 0; j<myArray[i].length; j++) {
row += myArray[i][j] + " ";
}
}
JOptionPane.showMessageDialog(null, "myArray contains:" + row);
nir[0].length
Note 0: You have to have minimum one array in your array.
Note 1: Not all sub-arrays are not necessary the same length.
Assuming that the length is same for each array in the second dimension, you can use
public class B {
public static void main(String [] main){
int [] [] nir= new int [2] [3];
System.out.println(nir[0].length);
}
}
Remember, 2D array is not a 2D array in real sense.Every element of an array in itself is an array, not necessarily of the same size.
so, nir[0].length may or may not be equal to nir[1].length or nir[2]length.
Hope that helps..:)
Expansion for multi-dimension array total length,
Generally for your case, since the shape of the 2D array is "squared".
int length = nir.length * nir[0].length;
However, for 2D array, each row may not have the exact same number of elements.
Therefore we need to traverse through each row, add number of elements up.
int length = 0;
for ( int lvl = 0; lvl < _levels.length; lvl++ )
{
length += _levels[ lvl ].length;
}
If N-D array, which means we need N-1 for loop to get each row's size.
//initializing few values
int[][] tab = new int[][]{
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1},
{1,0,1,0,1,0,1,0},
{0,1,0,1,0,1,0,1}
};
//tab.length in first loop
for (int row = 0; row < tab.length; row++)
{
//tab[0].length in second loop
for (int column = 0; column < tab[0].length; column++)
{
//printing one value from array with space
System.out.print(tab[row][column]+ " ");
}
System.out.println(); // new row = new enter
}

Categories