How to reference a 2D array from a static context?

浪子不回头ぞ 提交于 2019-12-10 15:17:28

问题


Every time I call myGrid in the generateBoard method, I get the error:

non-static variable myGrid cannot be referenced from static context

To my understanding, this shouldn't happen, because I've set the array to be public and should be able to be accessed from any other class. So have I set up the array incorrectly?

import java.util.Random;

public class Zombies {
    private int Level = 1;
    private int MoveNo = 0;
    public int[][] myGrid = new int[12][12];

    public static void generateBoard() {
        Random rand = new Random();
        int i, j;
        for (i = 0; i < 12; i++) {
            for (j = 0; j < 12; j++) {
                if ( i == 6 && j == 6) {
                    myGrid[i][j] = 'P';
                }
                if (rand.nextInt(4) == 0) {
                    myGrid[i][j] = 'I';
                }
                myGrid[i][j] = 'x';
            }
        }
    }

    public static String printBoard() {
        int i, j;
        for (i = 0; i < 12; i++) {
            for (j = 0; j < 12; j++) {
                if (j == 0) {
                    System.out.print( "| " );
                }
                System.out.print( myGrid[i][j] + " " );
                if (j == 12) {
                    System.out.print( "|" );
                }
            }
        }
    }
}

回答1:


myGrid variable is an instance variable rather than a class variable. That is, it can only be accessed by an instance of Zombies. On the other hand, the static methods (and class, a.k.a. static, variables) belong to a class, which are shared, in this case, among all Zombies instances.

Either pass myGrid (int[][]) as parameter to each of these static methods, or declare it as static.



来源:https://stackoverflow.com/questions/20307123/how-to-reference-a-2d-array-from-a-static-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!