I am a beginner there are two classes that I want to use getter to pass the value of the field from another class. Therefore, I did something like this How do getters and setters work?
But it didn’t pass the value. I got IllegalArgumentException: bound must be greater than origin
from the NimAIPlayer
since its bound and origin can’t be the same value. What could be the reason?
Here is part of the NimAIPlayer
class
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; }
And here is part of my NimGame
class
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; }
Any help is highly appreciated.
Advertisement
Answer
Add a parameterized constructor in NimGame class
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
You can initialize NimGame object like this using parameterized constructor
NimGame nimGame = new NimGame(new NimModel(),10,15,new NimPlayer(),new NimPlayer(),8);
Using NimGame nimGame = new NimGame() will initialize all fields with default values like null for object type and 0 for int type . This will result getting 0 for all interger fields when you print inside moveStone method .