I am writing this basic program with 3 classes in 3 separate files. It is supposed to be a program consisting of a class called PairOfDice, composed of two Die objects. Included methods to set and get the individual die values, a method to roll the dice,and a method that returns the current sum of the two die values. A driver class called RollingDice to instantiate and use a PairOfDice object.
It compiles without problems but when I try to run it results in a run-time error as follows:
Exception in thread "main" java.lang.NullPointerException at PairOfDice.rollDice(PairOfDice.java:42) at RollingDice.main(RollingDice2.java:16)
public class RollingDice
{
public static void main(String[] args)
{
PairOfDice pairofdice=new PairOfDice();
pairofdice.rollDice();
System.out.println(pairofdice.getDie1() +"\t" +pairofdice.getDie2());
}
}
public class PairOfDice
{
private Die die1, die2;
public PairOfDice()
{
Die die1=new Die();
Die die2=new Die();
}
public int getDie1()
{
return die1.getFaceValue();
}
public int getDie2()
{
return die2.getFaceValue();
}
public void setDie1(int dieValue)
{
die1.setFaceValue(dieValue);
}
public void setDie2(int dieValue)
{
die2.setFaceValue(dieValue);
}
public void rollDice()
{
die1.roll();
die2.roll();
}
public int sum()
{
return die1.getFaceValue()+die2.getFaceValue();
}
}
public class Die
{
private final int MAX = 6;
private int faceValue;
public Die()
{
faceValue = 1;
}
public void roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
}
public void setFaceValue(int value)
{
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}