I am trying to put an array(s) into another array so that I can output the numbers: 2, 7, 32, 8, 2. Must I be initializing the values somehow? Little confused. I tried three four loops but different results. There is a link somewhat similar: Why is my simple Array only printing zeros in java? My code is below. Thank you in advanced.
public class test
{
public static void main(String[] args) {
int[] a = {2, 7, 32, 8, 2};
int[] b = new int[a.length];
int[] c = new int[b.length];
int[][] d = {b};
for(int z = 0; z < b.length; z++){
System.out.print(b[z] + " ");
}
System.out.println();
for(int y = 0; y < c.length; y++){
System.out.print(c.length + " ");
}
System.out.println();
for(int x = 0; x < d.length; x++){
System.out.print(d.length + " ");
}
}
}
------------------------
OUTPUT
0 0 0 0 0
5 5 5 5 5
1
///////////////////////////
//NEW CODE
import java.util.*;
public class Main {
public static void main (String[]args) {
int[] arr1 = {1, 2, 3, 4 };
int[] arr2 = {5, 6, 7, 8, 9};
int[] arr3 = {10, 11, 12};
int[] arr4 = {13, 14, 15, 16, 17};
int[][] arrOfarrs = {arr1, arr2, arr3, arr4};
int a[] = new int[arrOfarrs.length];
for (int z = 0; z < arrOfarrs.length; z++) {
System.out.print (Arrays.toString (arrOfarrs[z]) + " ");
a[z] = arrOfarrs[z][z];
}
System.out.println ();
}
}
There are two different operations with arrays in Java:
intthe default value is0, forObject-null)Moreover, you can do both operations at the same time:
E.g. from your snippet:
And it's obvious this snippet will print content of an array
bwhich is{0,0,0,0,0}And this one will print content of an array
cwhich is{0,0,0,0,0}About 2D array. In java this is nothing more than array of arrays. Each row is an array.
So when you init an array like this:
it means, that you define a 2D array with 1 row and this 1 row contain array
b. By the way, each row in 2D array can have different length. I.e. in other way:To print 2D array you have to go through all rows (the first loop), and then all columns (the second loop).