简体   繁体   English

澄清多维数组

[英]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 . 数组索引从0开始。 So you have indexes 0,1,2 . 所以你有索引0,1,2 You'll run into an error when i is 3 . i 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. 正如@TJCrowder所评论的那样,为避免这种类型的混淆并为将来的代码更正使用array的length属性。 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 . 在您的情况下,数组长度为3 ,但是因为Java中的数组基于0 Hence the maximum index you can look for is 2 as it starts from 0 . 因此,您可以查找的最大索引为2因为它从0开始。 (ie you can only access elements in the range from 0-2 instead of accessing them in index 1-3) Replace. (即,您只能访问0-2范围内的元素,而不能访问索引1-3中的元素)替换。 :

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) 甚至更好: Arrays.deepToString(arr)

I advise you to go through the JLS - Chapter 10. Arrays : 我建议您仔细阅读JLS-第10章。数组

All arrays are 0-origin. 所有数组均为0起点。 An array with length n can be indexed by the integers 0 to n-1 . 长度为n的数组可以用0到n-1的整数索引

Your loops runs from [0,3]. 您的循环从[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). 它超过9(这是您拥有的元素数)。

Arrays in Java are zero-based , meaning that if you have an array of length N , indexes will run from [0, N-1] . Java中的数组是从零开始的 ,这意味着如果您有一个长度为N的数组,则索引将从[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. 您可以简单地使用数组的属性length

Try to figure it out, what will be the Exception . 尝试弄清楚,什么是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. 现在的问题是,您正在引用不存在的数组的index(3)。

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++) 对于(i = 0; i <3; i ++)对于(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 . for循环中的条件是错误的,当索引从0变为2时,您正在访问索引3 Change the condition of both for loops to this: 将两个for循环的条件都更改为此:

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). 每个编程初学者都会犯的全局性黄金错误,使他在编程中处于中间状态,正在运行从1到array(含)长度的循环。 That's what your scenario. 那就是你的情况。

The indices run from 0 to (array length - 1) in most languages like java/C/python/javascript/c++ 在大多数语言(例如java / C / python / javascript / c ++)中,索引从0到(数组长度-1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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