Reputation: 3
Im not exactly sure how to word this, I am trying to access different variables within a loop. Here is an example:
int[] box0 = {1,2,3};
int[] box1 = {4,5,6};
for(int i = 0; i < 2; i++){
box'i'[i] = 0; //Where I first change the elements of the box0 array then of box1 array.
}
I do not know how to concatenate, access, or otherwise use the other array. I am pretty new to java so please keep solutions as simple as possible. Thanks.
Upvotes: 0
Views: 141
Reputation: 19545
It would make sense to use array of arrays and then address an element of such array:
int[] box0 = {1, 2, 3};
int[] box1 = {4, 5, 6};
int[][] box = {box0, box1};
for (int i = 0; i < 2; i++) {
box[i][i] = 0; // however, here an elements are changed at diagonal cells
}
If all elements need to be changed by "row", a nested loop should be used:
int[] box0 = {1, 2, 3};
int[] box1 = {4, 5, 6};
int[][] box = {box0, box1};
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
box[i][j] = 0;
}
}
Upvotes: 1
Reputation: 111
It really depends on what you're trying to do. I cannot really determine what you are trying to achieve so I'm giving multiple possible options:
int[] box0 = {1,2,3};
int[] box1 = {4,5,6};
for(int i = 0; i < 3; i++)
{
box0[i] = 0;
}
This code will iterate over the elements 0 to 3 of the box0
array and set the value to 0.
box0 = [0, 0, 0]
box1 = [4, 5, 6]
int[] box0 = {1,2,3};
int[] box1 = {4,5,6};
int[][] allArrays = {box0, box1};
for(int i = 0; i < 2; i++)
{
allArrays[i][0] = 5;
}
This code will iterate over the elements 0 to 2 of the allArrays
array (which contains both arrays box0
and box1
) and set the value of their first element to 5.
box0 = [5, 2, 3]
box1 = [5, 5, 6]
allArrays = [[5, 2, 3], [5, 5, 6]]
Upvotes: 1