-2
所以我编写了一个掷骰子游戏,它要求我掷两个骰子并返回骰子的总和。滚动7或11会赢得比赛,滚动2,3或12会让你失去比赛。滚动4,5,6,8,9,10将“确定点”,用户继续滚动,直到他们滚动已建立的相同数字或直到他们掷出7,在这种情况下他们输了。我的Rolling Craps代码有什么问题?
以我为例,我得到,说
"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)"
我模具类看起来像这样的例外:
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;
}
}
而且我掷骰子的游戏看起来是这样的:
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);
}
}
}
你不会得到一个“空错误” - 你会得到一个异常,告诉你到底发生了什么问题和错误。你应该在问题中包含它。 – John3136
@ John3136编辑,谢谢指出。 – iHaunt
[什么是空指针异常,以及如何解决它?]可能重复(http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-doi-i-fix -它)?提示:“新Die()”在哪里? – IQV