有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在同一类的函数中使用构造函数中的二维数组变量

public class GameField {
    public static final int SIZE=8;

    public GameField() {
        Pawn[][] field = new Pawn[SIZE][SIZE];
    }

    void set(Cell cell, Pawn neuvalue) {
        this.field[cell.getx][cell.gety] = neuvalue;
    }
}

我想用x和y设置单元格的值,但它不起作用。我该怎么修呢


共 (1) 个答案

  1. # 1 楼答案

    如果要在类的多个方法中使用值,应将其定义为类属性:

    public class GameField {
        // this is a constant class attribute determining the initial size of the field
        public static final int SIZE = 8;
    
        // what you need is this: a variable class attribute, the field itself
        private Pawn[][] field;
    
        public GameField() {
            // you can define the size of the field like this (without a new declaration)
            field = new Pawn[SIZE][SIZE];
        }
    
        void set(Cell cell, Pawn neuvalue) {
            this.field[cell.getx][cell.gety] = neuvalue;
        }
    }
    
    public class GameField {
        // this is a constant class attribute determining the initial size of the field
        public static final int SIZE = 8;
    
        ...
    
        // what you can do if you cannot change the current constructor, write an alternative
        public GameField(int width, int height) {
            field = new Pawn[width][height];
        }
    
        ...
    }