So I am coding a game of craps which requires me to roll two dice and return the sum of the dice. Rolling a 7 or 11 wins you the game, rolling a 2, 3, or 12 however will lose you the game. Rolling a 4, 5 ,6, 8, 9, 10 will "Establish the point" where the user continues to roll until they roll the same number that was established or until they roll a 7, in which case they lose.
In my case, I get an exception that says
"Exception in thread "main" java.lang.NullPointerException
at Craps.getSum(Craps.java:24)
at Craps.playRound(Craps.java:29)
at Craps.main(Craps.java:70)
C:\Users\owner\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 2 seconds)"
My Die class looks like this:
import java.util.Random;
public class Die
{
private int number;
private Random generator;
public Die()
{
generator = new Random();
roll();
}
public int getNumber()
{
return number;
}
public void roll()
{
number = generator.nextInt(6)+1;
}
}
And my game of craps looks like this:
import java.util.Scanner;
public class Craps
{
private Die die1;
private Die die2;
private void rollDice()
{
die1.roll();
die2.roll();
}
private int getSum()
{
return (die1.getNumber() + die2.getNumber());
}
public void playRound()
{
if (getSum() == 7 || getSum() == 11)
{
System.out.println("You rolled a " +getSum()+ "! You win!!!");
}
else if(getSum() == 2 || getSum() == 3 || getSum() == 12)
{
System.out.println("You rolled a " +getSum()+ " You lose.");
}
else if(getSum() == 4 || getSum() == 5 || getSum() == 6 || getSum() == 8 || getSum() == 9 || getSum() == 10)
{
int established = getSum();
System.out.println("Establishing the point... Re-Rolling...");
rollDice();
do
{
rollDice();
System.out.println("You rolled a " +getSum());
}
while (getSum() != established && getSum() != 7);
if (getSum() == established)
{
System.out.println("You rolled a " +getSum()+ " which is also the established point, You win!");
}
else if(getSum() == 7)
{
System.out.println("You rolled a 7 after establishing the point, you lose.");
}
}
}
public static void main(String[] args)
{
Craps game = new Craps();
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to the game of Craps!");
System.out.println("Would you like to play a game? (Y/N");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Y"))
{
game.playRound();
}
else
{
System.out.println("Okay see you next time!");
System.exit(1);
}
}
}