java - 为什么我的第二个阵列没有被完全打印出来?

标签 java arrays eclipse for-loop

我正在尝试在一列和一行中创建以下数字的表示。

为什么我的第二个阵列没有被完全打印出来?

另外,数字不是以行列方式打印的。这是为什么?

public class MultidimensionalArrays
{

public static void main(String[] args)
{   
    //initializes rows and columns
    //first box = row, second box = column
    int firstarray[][] = {{3, 4, 5, 6,} , {8, 9}};

    //System.out.println(firstarray[0][1]) = 9;

    //initializes another rows and columns
    int secondarray[][] = {{11, 12, 13} , {88} , {100, 200, 300} , {33, 35, 37}};

    //displays the 1st array
    System.out.println("this is the 1st array: ");
    display(firstarray);

    System.out.println();

    //displays the 2nd array
    System.out.println("this is the 2nd array: ");
    display(secondarray);
}

//makes a method to display out the arrays
public static void display(int x[][])
{
    //makes a for-loop that prints out the row
    for(int row = 0; row < x.length; row++)
    {
        //makes a for-loop that prints out the column
        for(int column = 0; column < x.length; column++)
        {
            //sysouts the rows & columns
            System.out.print(x[row][column] + "\t");
        }
    }
}


}

错误代码:

this is the 1st array: 
3   4   8   9   
this is the 2nd array: 
11  12  13  Exception in thread "main"           java.lang.ArrayIndexOutOfBoundsException: 3
at MultidimensionalArrays.display(MultidimensionalArrays.java:37)
at MultidimensionalArrays.main(MultidimensionalArrays.java:24)

最佳答案

您的数组不是矩阵,因此列长不等于行长。事实上,不同的行有不同的列数,所以你必须使用每行的单独长度。

尝试:

for(int row = 0; row < x.length; row++)
{
    //makes a for-loop that prints out the column
    for(int column = 0; column < x[row].length; column++)
    {
        //sysouts the rows & columns
        System.out.print(x[row][column] + "\t");
    }
}

关于java - 为什么我的第二个阵列没有被完全打印出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33566168/

相关文章:

java - 从键值 json 响应访问字符串

javascript - 在 React Native 上使用 Expo 发送多个推送通知

ios - Swift Merge AVasset-Videos 数组

eclipse - 如何更新 Tomcat wtpwebapps\ROOT 文件夹?

java - 如何使用 Java 在 Mongo 中添加和删除数组中的元素?

java - 如何在android java中使用jetpack导航和bottomNavigationView

java - 访问本地类中的阴影变量

arrays - For-Next 循环和数组 - VBA

java - 执行 Maven 时出错 - 不可解析的设置 settings.xml

eclipse - Ironclad/Numpy 导入错误,但在 Eclipse 控制台中有效