在Java中将数组链接到另一个类

时间:2014-11-05 00:53:44

标签: java arrays object linker

我正在为一个类的tic-tac-toe开发游戏,在一个类中我创建了一个包含String数组的Board对象,然后将它传递给一个玩家类。但是我无法弄清楚如何允许我在新课程中使用这些信息。这里有人可以给我一些指示吗?

  public static void main(String[] args)
     {
        //new tic-tac-toe board
        Board board = new Board();

        //two new players (computer and human)
        Player computer = new Player(board, "X");   //Give computer player access to board and     assign as X.
        Player human = new Player(board, "O");      //Give human player access to board and assign as O.

和我正在尝试在

中使用它的课程
 package outlab5;
 import java.util.Scanner;
 public class Player {
     private String[][] currentBoard;
     private String move;
     Scanner input = new Scanner(System.in);


     public Player(Board inBoard, String inMove){
        move = inMove;
    }
    public void computerMove(){
        boolean valid = false;
    while(!valid){
        int moveCols = (int)(Math.random()*4);
        int moveRows = (int)(Math.random()*4);

        System.out.print(currentBoard[0][0]);

        }
    }

2 个答案:

答案 0 :(得分:0)

我认为你的Board类有一个表示你正在寻找的String [] []数组的字段。 在你的播放器类中,正确存储borad对象。

public class Player {
 private String[][] currentBoard;
 private String move;
 private Board board; //define a variable
 Scanner input = new Scanner(System.in);


 public Player(Board inBoard, String inMove){
    board = inBoard;
    move = inMove;
}

你没有显示Board类的代码,所以我必须猜测你如何访问字符串[] [],可能是Board类提供了一些get-Methods来访问字符串数组。

String[][] currentBoard = board.get....(); //this call must be placed in a method

答案 1 :(得分:0)

以下是您可以如何处理申请的示例。

董事会成员

public class Board {
    // TODO : Stuff and Stuff ( Where your 3x3 Matrix may be )
}

播放器摘要类

abstract class Player {

    private final Board board;
    private final String move;

    public Player(Board _board, String _move) {
        this.board = _board;
        this.move = _move;
    }

    public void playerMove() {
        // TODO : Default Movement Actions
    }

    public void playerWin() {
        // TODO : Default Event on Player Win
    }
}

计算机课程

public class Computer extends Player {
    public Computer(Board _board, String _move) {
        super(_board, _move);
    }

    @Override
    public void playerMove() {
        // TODO : Computer Related Movements ( Like AI )
        super.playerMove();
    }

    @Override
    public void playerWin() {
        // TODO : Computer Related Events for Computer ( Like Increase Dif )
        super.playerWin();
    }
}

人类

public class Human extends Player {
    public Human(Board _board, String _move) {
        super(_board, _move);
    }

    @Override
    public void playerMove() {
        // TODO : Human Related Movements ( Like I/O )
        super.playerMove();
    }

    @Override
    public void playerWin() {
        // TODO : Human Related Events on Win ( Like Score )
        super.playerWin();
    }
}