java - What is wrong with my Rolling Craps code? -
this question has answer here:
- what nullpointerexception, , how fix it? 12 answers
so coding game of craps requires me roll 2 dice , return sum of dice. rolling 7 or 11 wins game, rolling 2, 3, or 12 lose game. rolling 4, 5 ,6, 8, 9, 10 "establish point" user continues roll until roll same number established or until roll 7, in case lose.
in case, exception says
"exception in thread "main" java.lang.nullpointerexception @ craps.getsum(craps.java:24) @ craps.playround(craps.java:29) @ 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 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 game of craps looks 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 " +getsum()+ "! win!!!"); } else if(getsum() == 2 || getsum() == 3 || getsum() == 12) { system.out.println("you rolled " +getsum()+ " lose."); } else if(getsum() == 4 || getsum() == 5 || getsum() == 6 || getsum() == 8 || getsum() == 9 || getsum() == 10) { int established = getsum(); system.out.println("establishing point... re-rolling..."); rolldice(); { rolldice(); system.out.println("you rolled " +getsum()); } while (getsum() != established && getsum() != 7); if (getsum() == established) { system.out.println("you rolled " +getsum()+ " established point, win!"); } else if(getsum() == 7) { system.out.println("you rolled 7 after establishing point, lose."); } } } public static void main(string[] args) { craps game = new craps(); scanner scan = new scanner(system.in); system.out.println("welcome game of craps!"); system.out.println("would play game? (y/n"); string input = scan.nextline(); if (input.equalsignorecase("y")) { game.playround(); } else { system.out.println("okay see next time!"); system.exit(1); } } }
private die die1; private die die2;
holds null reference.
Comments
Post a Comment