简体   繁体   中英

Clarification on multi-dimensional arrays

This is my code and I'm trying to print the values of an array but I am not getting the proper output. Can someone show me where I am going wrong?

This is my code.

public class Arrrays {
    public static void main(String[] args) {
        try {   
            int arr[][] = new int[3][3];
            int i ;
            int j;
            arr[0][0]=1;  
            arr[0][1]=2;  
            arr[0][2]=3;  
            arr[1][0]=4;  
            arr[1][1]=5;  
            arr[1][2]=6;  
            arr[2][0]=7;  
            arr[2][1]=8;  
            arr[2][2]=9; 
            for(i=0;i<=3;i++)
                for(j=0;j<=3;j++)
                    System.out.println(arr[i][j]);  
        }
        catch (Exception e) {
            System.out.println("Error");
        }
    }
}

This is the output I'm getting

1
2
3
Error

Array indexes start from 0 . So you have indexes 0,1,2 . You'll run into an error when i is 3 .

That loop should be

for(i=0;i<3;i++){
            for(j=0;j<3;j++){

As @TJCrowder commented, to avoid this type of confusion and for future corrections of code use length property of array. So that though you increase or decrease the elements in array, your loop works :)

As a side note please make a habit of using {} , to avoid confusion.

You are basically moving over the maximum bound. Array length is 3 in your case but because arrays in Java are 0-based . Hence the maximum index you can look for is 2 as it starts from 0 . (ie you can only access elements in the range from 0-2 instead of accessing them in index 1-3) Replace. :

for(i=0;i<=3;i++)
            for(j=0;j<=3;j++)
               System.out.println(arr[i][j]);  

with

for(i=0;i<arr.length;i++)
            for(j=0;j<arr[i].length;j++)
               System.out.println(arr[i][j]);  

Or even better: Arrays.deepToString(arr)

I advise you to go through the JLS - Chapter 10. Arrays :

All arrays are 0-origin. An array with length n can be indexed by the integers 0 to n-1 .

Your loops runs from [0,3]. Meaning that you'll iterate through this table:

  i | j
 ---+---
  0 | 0  
  0 | 1
  0 | 2
  0 | 3
  1 | 0
  1 | 1
  1 | 2
  1 | 3
  2 | 0
  2 | 1
  2 | 2
  2 | 3
  3 | 0
  3 | 1
  3 | 2
  3 | 3

Count how many iterations you have. It exceeds 9 (Which is the number of elements you have).

Arrays in Java are zero-based , meaning that if you have an array of length N , indexes will run from [0, N-1] .

Also please try to avoid hardcoded numbers when you try to access array's length. You can simply use the property length of the array.

Try to figure it out, what will be the Exception .

Let's change your code as follows.

 try {
        int arr[][] = new int[3][3];
        int i;
        int j;
        arr[0][0] = 1;
        arr[0][1] = 2;
        arr[0][2] = 3;
        arr[1][0] = 4;
        arr[1][1] = 5;
        arr[1][2] = 6;
        arr[2][0] = 7;
        arr[2][1] = 8;
        arr[2][2] = 9;

        for (i = 0; i <= 3; i++)
            for (j = 0; j <= 3; j++)
                System.out.println(arr[i][j]);
    } catch (Exception e) {
        System.out.println("Error" + e);
    }

Let's check the out put:

 1
 2
 3
 Errorjava.lang.ArrayIndexOutOfBoundsException: 3

Now the issue is you are referring an index(3) of array which is not exist.

Let's check your iteration.

for (i = 0; i <= 3; i++) // you don't have index=3 max is 2
            for (j = 0; j <= 3; j++) // same issue here 

So need to change this to

for (i = 0; i < 3; i++) for (j = 0; j < 3; j++)

Now issue is solved.

Important

When you handling the exception make sure you are printing the exception or getting stack trace. See you can sort it the issue by your own.

The condition in your for loops is wrong, you are accessing the index 3 , when it goes from 0 to 2 . Change the condition of both for loops to this:

for(i=0;i<3;i++)
    for(j=0;j<3;j++)
        System.out.println(arr[i][j]);  

The global golden mistake every beginner in programming commits that make him intermediate in programming is running a loop from 1 to length of array(inclusive). That's what your scenario.

The indices run from 0 to (array length - 1) in most languages like java/C/python/javascript/c++

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