Multidimensional array usage in Java - java

Can anyone explain me what the following statement from the below code means..??
for (j = 0; j < arrayOfInts[i].length;
j++)
I'm learning Java language and having a very hard time figuring it out..
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;
j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor + " at " + i + ", " + j);
} else {
System.out.println(searchfor + " not in the array");
}
}
}

Java doesn't really have multidimensional arrays, it has arrays that can contain other arrays. That code takes the ith item from the misleadingly named arrayOfInts. This item is itself an array of integers, so it's taking the length of this array. (That was stored in another array.) So, for example in this code:
int[][] array2d = new int[][] {
new int[] {1}, // stored at array2d[0]
new int[] {2, 3, 4} // stored at array2d[1]
}
the following are true:
array2d.length == 2 (The "multidimensional" array contains two other arrays.)
array2d[0].length == 1 (The first of which has one element: 1.)
array2d[1].length == 3 (The second has three elements: 2, 3, 4.)

There is no multidimensional array in Java. All there is is arrays of arrays.
arrayOfInts is such an array of arrays of ints. So arrayOfInts[i] is an array of ints, and
for (j = 0; j < arrayOfInts[i].length; j++)
iterates over every element of this array, i.e. it iterates over all the elements in the array of ints stored at the index i of the array of arrays of ints.
You could see it as a big box containing N smaller boxes, each smaller box containg a given number of integers. arrayOfInt is the big box. arrayOfInt[i] is the ith smaller box in the big box. And the loop iterates over every integer in this smaller box.

In Java two-dimensional arrays are implemented is a one-dimensional array of one-dimensional arrays.
for (j = 0; j < arrayOfInts[i].length; j++)
arrayOfInts[i].length means length of the ith row of an arrayOfInts.
int[][] a = new int[2][4];
This two-dimensional array will have two rows and four columns. This actually allocates 3 objects: a one-dimensional array of 2 elements to hold each of the actual row arrays, and two one-dimensional arrays of 4 elements to represent the contents of the rows.
+-----+ +-----+-----+-----+-----+
|a[0] | -> | [0] | [1] | [2] | [3] |
| | +-----+-----+-----+-----+ In Java two-dimensional arrays are implemented is a
one-dimensional array of one-dimensional arrays -- like this.
+-----+
| | +-----+-----+-----+-----+
|a[1] | -> | [0] | [1] | [2] | [3] |
+-----+ +-----+-----+-----+-----+

j = 0; j < arrayOfInts[i].length
Cause you array is 2-dimensional, inner element of array will be array to.
So you getting the element(which is array) arrayOfInts[i] and calculates the length arrayOfInts[i].length, in other words:
int[] element = arrayOfInts[i];
int length = arrayOfInts[i].length;

Think of arrayOfInts[i][j] as a two-dimensional grid, like a spreadsheet. To help visualize, let's say that [j] represents the column index, and [i] represents the row index.
The explanation is then:
// iterate through every column j in the current row i:
for (j = 0; j < arrayOfInts[i].length; j++)

In your code , see the words int [][]arrayOfInts=...
It is a 2-dimensional array.2 dimensional arrays are nothing but arrays of arrays
It means simply there will be many normal 1-d arrays, and another array having references of each 1-d array.
So, the explanation of line, for(j=0;j<arrayOfInts[i].length;j++)is given below:
first, lets give focus to the wordsarrayOfInts[i].length
I already told you arrayOfInts is an array of arrays. So, arrayOfInts[i] points to the ith array.The word,arrayOfInts[i].length returns the length(i.e number of elements in an array) in the ith array of arrayOfInts.
The loop continues to happen until the j is less than then number of elements in the 1d array(less than (don't use equal to) because arrayOfInts[i][0] will be the first element).

Related

Slice an array into 2D array

I have a method which is intended to slice one bigger Array into a few smaller arrays. I would like it to return these arrays as an two dimensional array. So far slicing works but I have no idea how to write arr2[] elements to slice[][]. The problem is count of arrays slice[?][i] is unknown.
private short[][] slice(short array1[], int sliceSize) {
short arr2[]=null;
short slice[][]=null;
for (int offset = 0; offset < array1.length ; offset+=sliceSize) {
arr2 = Arrays.copyOfRange(array1, offset, offset+sliceSize);
for(int i=0; i<arr2.length; i++) {
System.out.print("\n value: "+ String.valueOf(arr2[i]));
// slice[?][i]=arr2[i];
}
}
return slice;
}
You can easily know the number of slice you need from the orignal array length.
int sliceCount = arr1.length / sliceSize + 1;
short[][] slice = new short[sliceCount][];
Note that we would end up with one to many cell if the length is a multiple of the slice size, we can simply substract 1 to arr1.length to correct that (didn't do it to keep the code simple)
Then, you just need to do some copy just like you do and store the result in it.
Since Arrays.copyOfRange return a new array instance each call, you can store the instance directly instead of iterating the array.
for (int i = 0; i < sliceCount; i++) {
arr2 = Arrays.copyOfRange(array1, i * sliceSize, ( i + 1 ) * sliceSize);
slice[i] = arr2;
}
return slice;
Example :
[1,2,3,4,5,6,7,8,9] into slice of 4 length
-> [
[1,2,3,4],
[5,6,7,8],
[9,0,0,0]
]

Creating a program that increments Arrays

An integer array stores values 3,2,3,4,5. I am trying to create a program that increments these values by 2 and then saves the result into the same array using a for loop. I tried but something is wrong with my code, here:
public class ArrayClass {
int a[] = {2, 3, 3, 4, 5};
}
public class ArrayObject {
public static void main(String[] Ella) {
int a[] = new int[5];
int i;
for (i = 2; i < a.length; i = i + 2) {
a[i] = i + 2;
System.out.println(a[i]);
}
}
}
This should work:
for (i = 0; i < a.length; i++) {
a[i] += 2;
System.out.println(a[i]);
}
You see, when increasing every single value of an array, the index has to be 0 and max the array's length. By adding one to i, the indexing of the array increases by one, which means the next number will be increased by two. what you did was add two to the "i" variable which means that only 3 of the varialbes would have been changed.
Please make below change to your code.It will work.
for (i = 0; i < a.length; i++) {
a[i] = a[i] + 2;
System.out.println(a[i]);
}
The error is that when you do i = i + 2, you are just incrementing the position index, not the actual value in that position.
you need to do:
a[i] = a[i]+2;
Let me explain what a[i] is:
|3|2|3|4|5|
1 2 3 4 5
The first row are the values. The second row is the index. "Index" means the position number of each of positions in the array.
Another problem is that, when you initialise i, it need to be i=0. That is because i array indices (plural of index) always start from 0. That means that a[0] is the first position in the array That would be number 3 from your data set.

Print a single value in parallel array

Does anyone know how I can output the single corresponding value in a parallel array? Say this is a pair (a | 1, b | 2, c | 3, etc., etc.). If the user enters a then 1 would print.
Do a traditional indexed linear search, then use the index to get the second value.
Example:
for(int i = 0; i < array1.length; i++){
if (array1[i].equals(SEARCH_TERM_HERE)){
return array2[i]; // Or print, etc.
}
}
if you search 'a' retrieve the index of 'a' from array1 and print it
for (int index = 0; index < array1 .length; index ++) {
if (array1[i].equals("a")){
System.out.println(array2[index]);
break;
}
}

Printing a one dimensional array as a two dimensinoal array

I'm trying to create a method that takes a one dimensional array and prints it out as a two dimensional array, but as square as possible so it looks nice. I've tried creating for loops to do this, but how would you figure out how many rows and columns there are? Could someone give me the logic in how to make one, so I can use that to create my own? An explanation would be lovely.
This will make a new array that is square and big enough to house all the elements of the old array. It takes the square root of the original array's length and rounds up.
int size = (int)Math.ceil(Math.sqrt(oldArray.length));
int[][]newArray = new int[size][size];
This method will print the elements in your one-dimensional array as close as possible to a square pattern on the console output. It places tabs in between elements to line them up on each row.
private void printMyArray(String[] onDimensionalArray) {
int cols = (int) Math.floor(Math.sqrt(onDimensionalArray.length));
int currentCol = 0;
for(String element : onDimensionalArray) {
System.out.print(element + "\t");
if(currentCol >= cols) {
System.out.println("");
currentCol = 0;
}
else {
currentCol++;
}
}
}
Example:
array = |1 2 3|
|4 5 6|
|7 8 9| (3*3)
Make a 1D array
int array1 = new int[3*3];
Or you can get length of the array
For row length: int row = array.length;
For column length: int column = array[0].length;
and then int array1 = new int[row*column];
Now iterate over array and copy all elements of array into array1.
_________________
array1 = |1|2|3|4|5|6|7|8|9|
Now don't ask me for code.
check this out
int array2d[][] = new int[10][3];
for(int i=0; i<10;i++)
for(int j=0;j<3;j++)
array2d[i][j] = array1d[(j*10) + i];

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