gpt4 book ai didi

Java:对象的封装和数组

转载 作者:行者123 更新时间:2023-12-02 04:20:18 25 4
gpt4 key购买 nike

我正在用 Java 制作一个 tic-tac-toe 游戏,以复习一些 Java 概念并练习 OOP。到目前为止,我有 4 个类:BoardPlayerCooperativeGame。我在测试 Board 类时遇到问题。棋盘由一系列坐标组成。目前 Board 有两种不同的构造函数。采用单个坐标的构造函数主要是为了测试目的。

Board.java

public class Board {

private Coordinate squares;
private Coordinate[] coordinateSet;

public Board(Coordinate squares) {
this.squares = squares;
}

public Board(Coordinate[] coordinateSet) {
this.coordinateSet = coordinateSet;
}

public Coordinate getSquares() {
return squares;
}

public Coordinate[] getCoordinates() {
return coordinateSet;
}

public Coordinate getCoordinate(int i) {
return coordinateSet[i];
}
}

坐标.java

public class Coordinate {

private int x;
private int y;
private int xFlag; // 0 if available, 1 if not available
private int yFlag; // 0 if available, 1 if not available
private boolean squareAvailability;

public Coordinate(int x, int y, int xFlag, int yFlag) {
this.x = x;
this.y = y;
this.xFlag = xFlag;
this.yFlag = yFlag;
}

public int getXCoordinate() {
return x;
}

public int getYCoordinate() {
return y;
}

public int getXFlag() {
return xFlag;
}

public int getYFlag() {
return yFlag;
}

public void setXFlag() {
if(xFlag == 0) {
xFlag = 1;
} else { }
}

public void setYFlag() {
if(yFlag == 0) {
yFlag = 1;
} else { }
}

public void add(Coordinate coordinate) {
// TODO Auto-generated method stub

}

public boolean isSquareAvailable(Coordinate coordinate) {
if(coordinate.getXFlag() == 0) {
if(coordinate.getYFlag() == 0) {
squareAvailability = true;
} else {
squareAvailability = false;
}
} else {
squareAvailability = false;
}

return squareAvailability;
}

}

BoardTest.java

import edu.learning.tictactoe.Board;
import edu.learning.tictactoe.Coordinate;

public class BoardTest {

public static void main(String[] args) {
Coordinate[] coordinates = new Coordinate[9];
Coordinate coordinate = new Coordinate(0, 0, 0, 0);
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
coordinates[i + j] = new Coordinate(i, j, 0, 0);
}
}
Board board = new Board(coordinate);
System.out.println(board.getSquares().getXCoordinate());
Board board2 = new Board(coordinates);
System.out.println(board2.getCoordinates().getCoordinate(0).getXCoordinate()); // error
}
}

我在 IDE 中的 BoardTest.java 最后一行收到错误,无法在数组类型 Cooperative[] 上调用 getCooperative(int)。问题是我试图从 Cooperative 对象数组中返回一个 Cooperative 对象,这是不可能的(?)那么我将如何返回一个 来自坐标数组的坐标

最佳答案

board.getCooperatives() 返回一个数组,编译器错误告诉您该数组没有 getCooperative(int) 方法。

简单地写

board.getCoordinate(0).getXCoordinate()

如果你想通过数组访问坐标,你可以写

board.getCoordinates()[0].getXCoordinate()

关于Java:对象的封装和数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32846095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com