我是初学者,有两个我想使用getter传递另一个类的字段值的类。因此,我做了这样的事情How do getters and setters work?
但是它没有传递值。我从IllegalArgumentException: bound must be greater than origin
获得了NimAIPlayer
,因为它的界限和原点不能是相同的值。可能是什么原因?
这里是NimAIPlayer
类的一部分
public class NimAIPlayer extends NimPlayer implements Testable {
NimGame nimGame = new NimGame();
private int stoneTaken;
public int moveStone() {
int balance = nimGame.getStoneBalance();
int initialStone = nimGame.getInitialStone();
int upperBound = nimGame.getUpperBound();
if (initialStone == balance) {
stoneTaken = ThreadLocalRandom.current().nextInt(1, upperBound + 1);
return stoneTaken;
} else if (balance < upperBound){
stoneTaken = ThreadLocalRandom.current().nextInt(1, + balance + 1);
return stoneTaken;
} else if (balance >= upperBound){
stoneTaken = ThreadLocalRandom.current().nextInt(1, upperBound + 1);
return stoneTaken;
}
return -1;
}
这是我的NimGame
类的一部分
public class NimGame extends Nimsys {
NimPlayer player1;
NimPlayer player2;
int stars;
int stoneBalance;
int initialStone;
int upperBound;
int takeStone;
public NimGame() {
}
public NimGame(NimModel nimModel, int initialStone, int upperBound , NimPlayer player1, NimPlayer player2) {
this.initialStone = initialStone;
this.upperBound = upperBound;
this.player1 = player1;
this.player2 = player2;
}
public int getInitialStone() {
return initialStone;
}
public int getUpperBound() {
return upperBound;
}
public int getStoneBalance() {
return stoneBalance;
}
非常感谢您的帮助。
在NimGame类中添加参数化的构造函数
NimGame.java
public NimGame(NimModel nimModel, int initialStone, int upperBound , NimPlayer player1, NimPlayer player2 , int stoneBalance) {
this.initialStone = initialStone;
this.upperBound = upperBound;
this.player1 = player1;
this.player2 = player2;
this.stoneBalance = stoneBalance;
}
NimAIPlayer.java
您可以使用参数化的构造函数像这样初始化NimGame对象
NimGame nimGame = new NimGame(new NimModel(),10,15,new NimPlayer(),new NimPlayer(),8);
使用NimGame nimGame = new NimGame()将使用默认值初始化所有字段,例如对象类型为null,int类型为0。这将导致在moveStone方法中进行打印时,对所有整数字段都获取0。
实例化nimGame类时,您使用了未实例化值的默认构造函数。那将使值成为空。首先实例化nimGame类中的值。
public class NimGame extends Nimsys {
NimPlayer player1;
NimPlayer player2;
int stars;
int stoneBalance;
int initialStone;
int upperBound;
int takeStone;
public NimGame() {
stars = default_value;
stoneBalance = default_value;
initialStone = default_value;
upperBound = default_value;
takeStone = default_value;
}
public NimGame(NimModel nimModel, int initialStone, int upperBound , NimPlayer player1, NimPlayer player2) {
this.initialStone = initialStone;
this.upperBound = upperBound;
this.player1 = player1;
this.player2 = player2;
}
public int getInitialStone() {
return initialStone;
}
public int getUpperBound() {
return upperBound;
}
public int getStoneBalance() {
return stoneBalance;
}