1

Ok so im told there is a slight logical error with my for inner loop. apparently if my [2][2] array had was 2X3 elements or 3X2 elements it wouldnt work could someone tell me how to fix this slight problem?

public static void dispArr(String [][] country){
    for(int i= 0; i<country.length; i++){ // both for loops count from 0 to 1 which are the only numbers required for this given array 
        for(int j= 0; j<country.length; j++){
            System.out.print(country[i][j]); //this will output [0][0],[0][1],[1][0] and[1][1] as identified above.
        }

        System.out.println("\n"); //create space between both
    }   
}
2
  • Try country[i].length in the inner loop Commented Dec 17, 2013 at 13:20
  • Thank you all very much! Commented Dec 17, 2013 at 13:33

4 Answers 4

8

Change it to:

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

                     // note the change here
    for (int j = 0; j < country[i].length; j++) {
        // ...
    }
}

Otherwise, the inner loop won't count up to as much as it needs to.

For a simple example, if you had this:

[[1, 2, 3], [4, 5, 6]]

It would become (with your original code):

for (int i = 0; i < 2; i++) {

              // oh no! not counting far enough
    for (int j = 0; j < 2; j++) {
        // ...
    }
}

You have to take the length of the inner array you're looping over, not the amount of inner arrays, if that makes any sense to you.

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

Comments

2

In Java a 2 dimensional array is essentially an array of arrays. Hence the need to put the index of the first dimension (array) when counting the second.

public static void dispArr(String [][] country){
    for(int i= 0; i<country.length; i++){ // both for loops count from 0 to 1 which are the only numbers required for this given array 

        for(int j= 0; j<country[i].length; j++){

            System.out.print(country[i][j]); //this will output [0][0],[0][1],[1][0] and[1][1] as identified above.
        }

        System.out.println("\n"); //create space between both
    }   
}

Comments

0

Your inner loop iterates over the first dimension in the matrix, and should probably be

for ( int j=0; j < country[i].length; j++ ) { ...

instead. Note the [i] after country.

Cheers,

Comments

0

country.length only gives you the first dimension. country[i].length will give you the second dimension.

Comments

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.