简体   繁体   中英

How can I define such an array?

How can I define such an array?

I need to make an array in JAVA like the one below:

Array(
    [0]=> Array(
            [0]=>1
            [1]=>1
            [2]=>1
            )
    [1]=> Array(
            [0]=>4
            [1]=>7
            [2]=>10
            )
     )

And how do I read this array using JAVA?

The PHP equivalent of this would be:

$a=array( array( 1, 1, 1 ), array( 4, 7, 10 ) );

And I can read it like this in PHP:

foreach( $a as $v ){
echo $v[0]. " ". $v[1]." ". $v[2]. "\r\n";
}

To sum up, I want to define an INT array of size 2, and each element of this array is another array of size 3. Then I want to read the inside array 3 values during a loop in three different INT variables. How can I do this?

You can use { } to define arrays

int[][] values = {{ 1, 1, 1 }, { 4, 7, 10 }};

To print them in a loop like you do

for (int[] a : values) 
    System.out.println(a[0] + " " + a[1] + " " + a[2]);

I suggest you read up on how arrays work in Java.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

You need to declare a two-dimensional array. The standard way to do this:

int[][] array = new int[][]{
    new int[] {1, 2, 3},
    new int[] {4, 5, 6}
};

But you could use more convenient one.

int[][] array = { {1, 2, 3}, {4, 5, 6} };

To iterate over the array you may use:

for(int[] i : array) {
    for(int j : i) System.out.print(i + " ");
    System.out.println();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM