3

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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();
}

1 Comment

Thank you both for the answers. This solves my problem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.