访问错误的Java组合

时间:2018-03-24 14:12:25

标签: java class

我有这门课,其主要目的是作曲。 这些行在主类中:

Game myGame = new Game(getRandomPositions(), player);

System.out.println("Current Play No: " + (myGame.getPlayCount()+1) + "\n");
myGame.getBoard().displayBoard();

我在这行中收到错误:

myGame.getBoard().displayBoard();

这是游戏类的一部分:

public class Game {
    private Player player;
    private Board board;
    private static final int MAX_RABBITS = 3;
    public Game(int[] rabbitPositions, Player player)
    {
        this.player=player;
    }

    public Board getBoard() {
        return board;
    }

    public Player getPlayer() {
        return player;
    }
}

这是董事会课程的一些部分:

 public class Board {
    public static final int NUM_SPACES = 16;

    public Board(int rabbitPositions[])
    {
        //FIXME
    }
    public void displayBoard()
    {
        System.out.println("A");
    }
}

我想知道我错过了什么?董事会的吸气剂是否正确? 我直接访问displayBoard时工作正常。 我想知道如何初始化板构造函数?

2 个答案:

答案 0 :(得分:0)

您需要在构造函数中初始化对象board

public Game(int[] rabbitPositions, Player player){
    this.player=player;
    this.board= new Board(rabbitPositions);
}

答案 1 :(得分:0)

您可以在Game构造函数中初始化Board类,因为它具有初始化Board类所需的相同数据类型rabbitPositions

public class Game {
        private Player player;
        private Board board;
        private static final int MAX_RABBITS = 3;
        public Game(int[] rabbitPositions, Player player)
        {
            this.player=player;
            //initialising the board class
            this.board= new Board(rabbitPositions);
        }

        public Board getBoard() {
           //now it will not none
            return board;
        }

        public Player getPlayer() {
            return player;
        }
    }

public class Board {
    public static final int NUM_SPACES = 16;

    public Board(int rabbitPositions[])
    {
        //do stuff with rabbitPositions
    }
    public void displayBoard()
    {
        System.out.println("A");
    }
}