简体   繁体   中英

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.

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:

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:

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 ....).

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.

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