简体   繁体   English

如何在java中打印二维数组?

[英]How to print a 2D array in java?

I am stuck with this.我坚持这一点。 I want to print an array with its size declared inside the code.我想打印一个数组,其大小在代码中声明。

package userdefinedarray;

import java.util.Arrays;


public class userdefinedarray 
{    
    public static void main(String[] args) 
    {        
    int[][] myArray = new int[5][10];    
    for(int i=0;i<myArray.length;i++)
    {
        myArray[i] = null;
    }
    System.out.println(Arrays.toString(myArray));
    System.out.println(Arrays.deepToString(myArray));
}

} }

Here's the output.这是输出。 What happened to the >>[10]<< in "new int[5][10]"? “new int[5][10]”中的 >>[10]<< 发生了什么?

[null, null, null, null, null]
[null, null, null, null, null]

Your 2-D array consists of arrays of arrays.您的二维数组由数组数组组成。 Think of it in this way.这样想。 For every array element imagine a new array as an element.对于每个数组元素,想象一个新数组作为一个元素。 So, in order to print it, you would need to iterate over each of those arrays, in other words, over rows and columns.因此,为了打印它,您需要遍历每个数组,换句话说,遍历行和列。

for(int i=0; i<myArray.length;i++){
    for(int j=0;j<myArray[0].length;j++)
       System.out.print(myArray[i][j] + " ");
    System.out.println();
}

If you want to fill your arrays with any particular non null value, you can do it inside the outer for loop.如果你想用任何特定的非空值填充你的数组,你可以在外部 for 循环中进行。

Also, you cannot do此外,你不能做

myArray[i] = null;

If you want to actually do that, use如果你想真正做到这一点,请使用

myArray[i] = new int[myArray[0].length];

You are first creating an array containing 5 arrays having each 10 int (initialized to 0).您首先创建一个包含 5 个数组的数组,每个数组有 10 个 int(初始化为 0)。

Then in your for loop, you set each index of the first dimension to null.然后在 for 循环中,将第一个维度的每个索引设置为 null。 You then have an array containing five null éléments.然后您有一个包含五个空元素的数组。

If for some reason you really want to work with null values i advice you to use List instead.如果由于某种原因您真的想使用空值,我建议您改用 List。

If you want to set values of your array you should nest another loop inside the first one, but then setting to null the native int type will throw an exception i believe如果你想设置你的数组的值,你应该在第一个循环中嵌套另一个循环,但是然后将本机 int 类型设置为 null 我相信会抛出异常

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

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