简体   繁体   English

设置二维数组的所有值(java)

[英]Setting all values of a 2d array (java)

I am trying to fill a 7x6 blank 2d Array in java with a value of -1. 我试图用值-1填充java中的7x6空白2d数组。

I initialized the array in a non-main class by typing: 我通过键入以下内容在非主类中初始化了数组:

int[][] anArray = new int[7][6];

Then I created a method setArray() which looks like the following: 然后,我创建了一个方法setArray(),如下所示:

public int[][] setArray()
{
    for (int i = 0; i < 7; i++)
    {             
        for (int j = 0; j < 6 ; j++)
        {
            anArray[i][j] = -1;
        }
    }
return anArray;
}

but when I run this method through the main class, it returns the board as: 但是当我通过主类运行此方法时,它将返回板为:

[[I@71988d36

Does anyone know why this is happening? 有人知道为什么会这样吗? I'm fairly sure the above code is correct. 我相当确定上面的代码是正确的。

edit: Forgot a pair of curly braces. 编辑:忘记了一对花括号。

Every class extending Object in Java (that is, all of them) inherits this method: Java中扩展Object的每个类(即所有类)都继承此方法:

public String toString()

Which is called when you invoke to decide what to actually print 当您调用以决定要实际打印的内容时调用哪个

System.out.println()

The problem is, unless you override it, it will return something not very helpful which will get printed (except in a few cases such as String, int ....). 问题是,除非您重写它,否则它将返回不是很有用的内容,并将其打印出来(在某些情况下,例如String,int ....)。

In this particular case, rather than overriding it, and as the comments above explain, it's easier to call a wrapper function that takes the array as a parameter and delivers a nice String as a result. 在这种特殊情况下,与其覆盖它,不如覆盖上面的注释,调用包装器函数比较容易,该包装器函数将数组作为参数并提供一个漂亮的String作为结果。

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

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