So I made a die class that is supposed to create die, and then allow me to roll them, pull their values and number of sides. My problem now is that I cannot roll the die during testing as it throws a NullPointerException.
Here's the die class code:
package com.catalyse.die;
import java.util.Random;
public class Die
{
// instance variables
private static int dieNum = 0;
private int myDieValue;
private int myDieSides;
private Random rand;
// Dice Class Constructors
public Die()
{
dieNum++;
this.myDieValue = 1;
this.myDieSides = 4;
}
public Die(int numSides)
{
if ((numSides < 4) || (numSides > 100)) {
System.out.println("Error! You cannot have more than 100 sides or less than four!");
System.exit(0);
}
else {
myDieSides = numSides;
myDieValue = 1;
}
}
// getter methods
public int getDieSides()
{
System.out.println(myDieSides);
return 0;
}
public int getDieValue()
{
System.out.println(myDieValue);
return 0;
}
// setter methods
private void setDieSides(int newNumSides)
{
myDieSides = newNumSides;
}
public void rollDie()
{
myDieValue = (rand.nextInt(myDieSides) + 1);
}
// other methods
public void printDie(int dieNum)
{
if (dieNum == 1) {
System.out.println("Die Value: "+myDieValue);
}
else {
System.out.println("Die "+dieNum+" Value: "+myDieValue);
}
}
}
Here is the testing class.
package com.catalyse.die;
public class TestDieClass
{
public static void main(String [] args)
{
Die One = new Die();
Die Two = new Die(50);
Die Three = new Die(99);
One.getDieSides();
One.getDieValue();
Two.getDieSides();
Two.getDieValue();
Three.getDieSides();
Three.getDieValue();
One.rollDie();
Two.rollDie();
Three.rollDie();
One.getDieValue();
Two.getDieValue();
Three.getDieValue();
}
}
Here is the error
4
1
50
1
99
1
Exception in thread "main" java.lang.NullPointerException
at com.catalyse.die.Die.rollDie(Die.java:83)
at com.catalyse.die.TestDieClass.main(TestDieClass.java:27)
myDieValue = (rand.nextInt(myDieSides) + 1);
You haven't initialized rand so rand is null
So,
private Random rand= new Random();
Related
i'm learning junit and problem have occured at the beginning.
At the start i want to initialize objected which will be used in tests.
But #BeforeClass doesn't do that.
public class InitTests {
private Croupier croupier;
private Player p1, p2;
#BeforeClass
public void setUp() {
croupier = new Croupier();
croupier.PlayersInit(5, 100);
p1 = croupier.getPlayer(0);
p2 = croupier.getPlayer(1);
} #Test // p1,p2, croupier = null, have no idea why.
public void PlayerInitTest() {
assertEquals(0, p1.getId());
assertEquals(1, p2.getId());
}}
Other classes :
public class Player {
private ArrayList<Card> hand = new ArrayList<>();
private int coins = 0;
private static int playerNumber = 0;
private int id;
private boolean inGame = true;
public Player(int coins) {
this.coins = coins;
id = ++playerNumber;
}
public int addCoins(int amount) {
coins+=amount;
return amount;
}
public int substractCoins(int substract) {
coins-=substract;
return substract;
}
public int getCoins() {
return coins;
}
public int getId() {
return id;
}
public boolean isInGame() {
return inGame;
}
public void setGameStatus(boolean status) {
if(getCoins() < 0 )
inGame = false;
else
inGame = status;
}
public void clearHand() {
hand.clear();
}}
public class Croupier {
private String name;
private ArrayList<Card> deck = new ArrayList<>();
private ArrayList<Player> allPlayers = new ArrayList<>();
private ArrayList<Player> actual = new ArrayList<>();
private int stack = 0;
private int bigPlayerStack = 0;
private int smallPlayerStack = 0;
public Croupier() {
System.out.println("tutej.");
}
public Croupier CroupierInit() {
// static
PlayersInit(5, 100);
return new Croupier();
}
private void CreateDeck() {
String[] suits = { "hearts", "spades", "diamonds", "clubs" };
for (int i = 0; i < suits.length; i++)
for (int j = 2; j < 15; j++)
deck.add(new Card(j, suits[i]));
}
private void DeckShuffle() {
Collections.shuffle(deck);
}
public boolean TurnPlayed() {
if (!preparedGame())
return false;
return true;
}
public void StartGame() {
preparedGame();
System.out.println("Game ended.");
}
public boolean preparedGame() {
clearTable();
if(!setActualPlayers())
return false;
setSmallAndBig();
takeFromSmallAndBig();
CreateDeck();
DeckShuffle();
return true;
}
// set players who are playing
public boolean setActualPlayers() {
for (Player e : allPlayers)
if (e.isInGame())
actual.add(e);
if (actual.size() < 2)
return false;
return true;
}
// take coisn from small and big blind
public void takeFromSmallAndBig() {
stack += actual.get(bigPlayerStack).substractCoins(20);
stack += actual.get(smallPlayerStack).substractCoins(10);
}
// set who has small or big blind
public void setSmallAndBig() {
bigPlayerStack++;
if (bigPlayerStack > actual.size())
bigPlayerStack = 0;
smallPlayerStack = bigPlayerStack - 1;
if(smallPlayerStack < 0 )
smallPlayerStack = actual.size() -1;
}
// clear table before game
public void clearTable() {
actual.clear();
for (Player e : allPlayers)
e.clearHand();
}
public void PlayersInit(int numberOfPlayers, int coins) {
for (int i = 0; i < numberOfPlayers; i++) {
allPlayers.add(new Player(coins));
}
}
public Player getPlayer(int index) {
return allPlayers.get(index);
}}
I'm sure these tests are correct because when i put setUp method ( code from that method) inside #Test it just works.
I hope it's a simple syntax problem which as a beginner can't set at the moment.
Greetings.
Your test class uses a mix of JUnit 4 and 5 annotations.
The JUnit 5 API is not compatible with prior versions of the library, and defines a new set of annotations. Assuming your test executes, you are probably using a JUnit 5 launcher and therefore need to use annotations from org.junit.jupiter.api package.
If you wish to use JUnit 5
Try #org.junit.jupiter.api.BeforeEach or#org.junit.jupiter.api.BeforeAll, with a static method for the latter. Their semantic is defined here.
If you wish to use JUnit 4
You need revert all the annotations to JUnit 4 - which implies using org.junit.Test.
Your JUnit launcher needs to be configured for JUnit 4.
Apologies if this is trivial to most but I just can't figure this issue out!!
I am creating a mock game where I have a start, end, and hops along. There are portals where if you go on a white portal you jump further ahead and there are black ones where you go backwards. I have set up the class as a POJO;
private int totalSize;
private int minDice;
private int maxDice;
private int whitePortalStart;
private int whitePortalEnd;
private int blackPortalStart;
private int blackPortalEnd;
private int startPosition = 1;
private int currentPosition;
public GameObject(){}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) throws Exception {
if(totalSize <= 0){
throw new Exception("Can't have a total distance of less than or equal to 0");
} else {
this.totalSize = totalSize;
}
}
public int getMinDice() {
return minDice;
}
public void setMinDice(int minDice) throws Exception {
if(minDice <= 0){
throw new Exception("Can't have a min dice value of less than or equal to 0");
} else {
this.minDice = minDice;
}
}
public int getMaxDice() {
return maxDice;
}
public void setMaxDice(int maxDice) throws Exception {
if(getMinDice() > maxDice){
throw new Exception("Cant have minimum dice number greater than the larger dice number");
} else {
this.maxDice = maxDice;
}
}
public int getWhitePortalStart() {
return whitePortalStart;
}
public void setWhitePortalStart(int whitePortalStart) throws Exception {
this.whitePortalStart = whitePortalStart;
}
public int getWhitePortalEnd() {
return whitePortalEnd;
}
public void setWhitePortalEnd(int whitePortalEnd) throws Exception {
this.whitePortalEnd = whitePortalEnd;
}
public int getBlackPortalStart() {
return blackPortalStart;
}
public void setBlackPortalStart(int blackPortalStart) throws Exception {
this.blackPortalStart = blackPortalStart;
}
public int getBlackPortalEnd() {
return blackPortalEnd;
}
public void setBlackPortalEnd(int blackPortalEnd) throws Exception {
this.blackPortalEnd = blackPortalEnd;
}
public GameObject builder(int n) throws Exception {
setTotalSize(n);
return this;
}
public GameObject whitePortal(int m, int o) throws Exception {
setWhitePortalStart(m);
setWhitePortalEnd(o);
return this;
}
public GameObject blackPortal(int o, int m) throws Exception {
setBlackPortalStart(o);
setBlackPortalEnd(m);
return this;
}
public GameObject dice(int i, int j) throws Exception {
setMinDice(i);
setMaxDice(j);
return this;
}
public int rollDice(){
Random random = new Random();
int min = getMinDice();
int max = getMaxDice();
return random.nextInt(max - min + 1) + min;
}
public void build(){
int totalDistance = getTotalSize();
currentPosition = startPosition;
while(currentPosition < totalDistance){
int diceValue = rollDice();
if(currentPosition + diceValue > getTotalSize()){
System.out.println("CurrentPosition : " + (currentPosition + diceValue) + ", is larger than the total size of the road - " + totalSize);
continue;
} else if(currentPosition + diceValue == getWhitePortalStart()){
System.out.println("You landed on a white portal. Advancing from position " + (currentPosition + diceValue) + " to " + getWhitePortalEnd());
currentPosition = getWhitePortalEnd();
} else if(currentPosition + diceValue == getBlackPortalStart()){
System.out.println("You landed on a black portal. Moving from position " + (currentPosition + diceValue) + " to " + getBlackPortalEnd());
currentPosition = getBlackPortalEnd();
} else {
System.out.println("You landed on " + (currentPosition + diceValue));
currentPosition += diceValue;
}
}
}
So in my main method I call the it like create and call this class like;
WorldOfOz oz = new WorldOfOz();
oz.go.builder(30)
.dice(1, 4)
.whitePortal(5, 12)
.blackPortal(13, 2)
.build();
My issue is when I want to add in more than 1 whitePortal/blackPortal
WorldOfOz oz = new WorldOfOz();
oz.go.builder(30)
.dice(1, 4)
.whitePortal(5, 12)
.whitePortal(18, 26)
.blackPortal(13, 2)
.build();
The values 18 - 26 override 5 - 12. How can I set this up so I can have multiple white and black portals?
It seems that your data structure is not enough to solve this problem.
You need to define a collection of whitePortals and a collection of blackPortals. If you do so calling the method whitePortal(5, 12) add a new white portal insted of setting the white portal values of the only white existing portal.
You need to define a class Portal
public class Portal {
private int portalStart;
private int portalEnd;
...
public Portal(int s, int e) {
this.portalStart = s;
this.portalEnd = e;
}
}
Then you can use it in the GameObject as follow:
public GameObject {
List<Portal> whitePortals;
List<Portal> blackPortals;
public GameObject() {
whitePortals = new ArrayList<Portal>();
blackPortals = new ArrayList<Portal>();
}
public GameObject addWhitePortal(int m, int o) throws Exception {
whitePortals.add(new Portal(m, o));
return this;
}
...
// You need to change other methods to follow a different data structure
}
Well, you can use the following approach:
Introduce a new "Portal" type with start/end attributes
Replace white/black portal attributes in your class with lists for white and black portals (or any other type of collection you like)
Replace getWhite/Black methods with access to lists
Refactor whitePortal and blackPortal method to create new instances of a portal object and add them to an appropriate collection
You can, of course, use arrays instead of collections, but that's a bit more cumbersome.
Also, assuming portals are collections, you probably need to add helper methods for operating on those. Depending on what your actual needs are.
public class Portal
{
private int start;
private int end;
public Portal(int start, int end) { ... }
public getStart() {...}
public getEnd() {...}
public setStart(int end) {...}
public setEnd(int start) {...}
}
public class GameObject
{
...
private List<Portal> whitePortals = new ArrayList<Portal>();
private List<Portal> blackPortals = new ArrayList<Portal>();
...
public GameObject whitePortal(int m, int o) throws Exception {
whitePortals.add(new Portal(m, o));
return this;
}
public GameObject blackPortal(int o, int m) throws Exception {
blackPortals.add(new Portal(m, o));
return this;
}
...
}
I am trying to use the Die class when writing a PairOfDice class. Here is the Die class:
public static class Die {
private final int MAX = 6;
private int faceValue;
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
if(value > 0 && value <= MAX)
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Now what I am trying to do is to use this class to write a similar class called PairOfDice. I want similar methods of rolling the dice, setting the face value, and so on. However I have never done this before so I'm not sure how to approach this. Here is what I have so far:
public static class PairOfDice {
Die die1 = new Die();
Die die2 = new Die();
public PairOfDice()
{
????
}
public int rollPair()
{
????
}
}
I'm not sure how to appropriately use these objects. Please keep in mind I am a beginner in java/programming.
You don't appear to need anything in the constructor, you've initialized the die fields where you declared them. Just call them in your method. Something like,
public int rollPair()
{
return die1.roll() + die2.roll();
}
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
public static final void main(String... aArgs){
System.out.println("Generating random number");
//note a single Random object is reused here
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(1000000);
int randomInt2 = randomGenerator.nextInt(1000000);
System.out.println("generated " + randomInt + " and " + randomInt2);
if (isPrime(randomInt)==true)
{
System.out.println("it's prime");
}
else
{
System.out.println("it's not ");
}
System.out.println("Done.");
System.exit(0);
}
}
public static boolean isPrime(int random)
{
//check if n is a multiple of 2
if (random%2==0) return false;
//if not, then just check the odds
for(int i=3;i*i<=random;i+=2)
{
if(random%i==0)
{
return false;
}
else
{
return true;
}
}
}
You have isPrime method out of your class and it needs to be within the scope of the class. So define it before the main method.
Something like:
public final class RandomInteger {
public static boolean isPrime(int random) {
....
}
public static final void main(String... aArgs){
....
So I'm making a die class that can create and roll a die, return the value and the size. I'm trying to figure out how to tell the program how many of them have been created so that I can have a response be different based on how many there are. IE I want the response from printDie to be Die Value: 5 if there is only one die, and Die 1 Value: 5 if there is more than one.
Here's my code so far.
package com.catalyse.die;
import java.util.Random;
public class Die
{
// instance variables
private int myDieValue;
private int myDieSides;
private Random myRandom;
// Dice Class Constructors
public Die()
{
this.myDieValue = 1;
this.myDieSides = 4;
}
public Die(int numSides)
{
if ((numSides < 4) || (numSides > 100)) {
System.out.println("Error! You cannot have more than 100 sides or less than four!");
System.exit(0);
}
else {
myDieSides = numSides;
}
}
// getter methods
public int getDieSides()
{
return myDieSides;
}
public int getDieValue()
{
return myDieValue;
}
// setter methods
private void setDieSides(int newNumSides)
{
myDieSides = newNumSides;
}
public void rollDie()
{
Random rand = new Random();
int i = (rand.nextInt(myDieSides) + 1);
myDieValue = i;
}
public void printDie(int dieNum)
{
if (dieNum == 1) {
System.out.println("Die Value: "+myDieValue);
}
else {
System.out.println("Die "+dieNum+" Value: "+myDieValue);
}
}
}
You can have static field in your class which could be incremented in the constructor always. The reason why is it should be static is because, static fields are shared by all instances of a class, thus a local copy of the field won't be created for each of the instances you create.
private static int counter = 0;
public Die()
{
counter++;
// Other stuffs
}
// Have a getter method for the counter so that you can
// get the count of instances created at any point of time
public static int getCounter() {
return counter;
}
And then you can call the above method in your calling method like this
void someMethodInAnotherClass() {
int instanceCount = Die.getCounter(); // You need to call static method using the Class name
// other stuffs.
}
Use an static member, that is a 'class' variable, not a 'instance' variable:
private static int count = 0;
In the constructor:
public Die()
{
count++;
this.myDieValue = 1;
this.myDieSides = 4;
}
And a getter:
public static int getCount() {
return count;
}
Use a static variable
public class Die{
static int dieCount = 0;
public Die(){
dieCount++;
}
}
Every time a Die object is created, the count will increase
public static void main(String[] args){
Die die1 = new Die();
Die die2 = new Die();
int count = Die.dieCount;
}
See what is my solution for counting objects in my application
import java.util.Map;
import java.util.TreeMap;
public abstract class ObjectCounter {
private static Map<String, Long> classNameCount = new TreeMap<String, Long>();
public ObjectCounter() {
String key = this.getClass().getName();
if (classNameCount.containsKey(key)) {
classNameCount.put(key, classNameCount.get(key) + 1);
} else {
classNameCount.put(key, 1L);
}
}
public static <T extends ObjectCounter> long getCount(Class<T> c) {
String key = c.getName();
if (classNameCount.containsKey(key)) {
return classNameCount.get(key);
} else {
return 0;
}
}
public static long totalObjectsCreated() {
long totalCount = 0;
for (long count : classNameCount.values()) {
totalCount += count;
}
return totalCount;
}
}
Now extends ObjectCounter class
See below
package com.omt.factory;
public class Article extends ObjectCounter {
}
Now all your other classes are extending Article classes
package com.omt.factory;
public class Bio extends Article {
}
Now here is our main class
package com.omt.factory;
public class Main {
public static void main(String... a) {
Bio b = new Bio();
Bio b1 = new Bio();
Bio b2 = new Bio();
Bio b3 = new Bio();
Bio b4 = new Bio();
com.omt.temp.Bio bio = new com.omt.temp.Bio();
// Total Objects are created
System.out.println("Total Objects Created By Application :" + ObjectCounter.totalObjectsCreated());
// Get Number Of Objects created for class.
System.out.println("[" + com.omt.temp.Bio.class.getName() + "] Objects Created :"
+ ObjectCounter.getCount(com.omt.temp.Bio.class));
System.out.println("[" + Bio.class.getName() + "] Objects Created :" + ObjectCounter.getCount(Bio.class));
System.out.println("[" + Maths.class.getName() + "] Objects Created :" + ObjectCounter.getCount(Maths.class));
}
}
From this article