Samuel Van Bladel
Samuel Van Bladel

Reputation: 67

Printing out values of different rows and column in 2d array using for loops

I have this 2d array of the first row being first names and the second being last names.

String[][] ladrones2 = {
        {"Phil", "Kim", "Phil", "Perry"},
        {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

the prefered out come of this would be to have them printend out like e.g

Phill Garcia
Kim Gimena
etc...

Now I was able to do this by catching the ArrayIndexOutOfBoundsException exception and it works and the output is:

name Phil Garcia
name Kim Gimena
name Phil Basinger
name Perry Ornitorrinco

Which is great but I wondered if there was a way to do this without having to catch the exception? I've been searching to make this cleaner but wasn't able to do so.

Code at the moment:

public static void robo2() {
    String[][] ladrones2 = {
            {"Phil", "Kim", "Phil", "Perry"},
            {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

    try {
        for (int i = 0; i < ladrones2.length; i++) {
            for (int j = 0; j < ladrones2[i].length; j++) {
                System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);
            }
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println("");
    }
}

as you can see I used in the inner for loop a +1 on the i variable which in turn throws the exception.

Any ideas? I would like just to keep this way of working at the moment with 2 forloops due to being new to Java.

Upvotes: 0

Views: 288

Answers (2)

Sudhir
Sudhir

Reputation: 1419

If you are sure that ladrones2 array always has 2 rows, then below code would be simpler:

public static void main(String[] args) {
    String[][] ladrones2 = {
            {"Phil", "Kim", "Phil", "Perry"},
            {"Garcia", "Gimena", "Basinger", "Ornitorrinco"}};

    for (int i = 0; i < ladrones2[0].length; i++) {
        System.out.println("name: " + ladrones2[0][i] + " " + ladrones2[1][i]);
    }
}

Upvotes: 1

Simon Gaufreteau
Simon Gaufreteau

Reputation: 21

On this line :

System.out.println("name: " + ladrones2[i][j] + " " + ladrones2[i + 1][j]);

You are taking an element from the first and second array at the same time but you are looping over all the elements in the sequence on this line :

for (int i = 0; i < ladrones2.length; i++) 

To correct this problem, you simply have to reduce the range of i to ladrones.length-1, otherwise you will reach the end of the array and try to access the next element which doesn't exist here.

You'll end up with this line instead :

for (int i = 0; i < ladrones2.length-1; i++) {

Upvotes: 1

Related Questions