I been trying to create a Pig game to help keep me refresh in Java code, and Im having trouble with my while loop not ending when it should.
while (pTotal < 100 || cTotal < 100) { rollDice = "roll"; roll = true; while (rollDice.equalsIgnoreCase("roll")) { dice.roll (); System.out.println ("You rolled " + dice.getValue1 () + " and " + dice.getValue2() + "."); if (dice.check()) { if (dice.getValue1() == 1) { pTotal = 0; rollDice = "pass"; roundTotal = 0; roll = false; } } if (!dice.check () && dice.getValue1 () == 1 || dice.getValue2() == 1) { roundTotal = 0; rollDice = "pass"; roll = false; } if (roll) { roundTotal += dice.getValue1 () + dice.getValue2 (); System.out.println (roundTotal); System.out.println ("Would you like to roll again or pass the dice?" + "(roll/pass): "); rollDice = scan.next (); } if (rollDice.equalsIgnoreCase("pass")) { pTotal += roundTotal; roundTotal = 0; } } rollDice = "roll"; roll = true; while (rollDice.equalsIgnoreCase("roll") && pTotal < 100) { dice.roll (); if (dice.check()) { if (dice.getValue1() == 1) { cTotal = 0; rollDice = "pass"; roundTotal = 0; roll = false; } } if (!dice.check () && dice.getValue1 () == 1 || dice.getValue2() == 1) { roundTotal = 0; rollDice = "pass"; roll = false; } if (roll) { roundTotal = dice.getValue1 () + dice.getValue2 (); } if (roundTotal >= 20) { cTotal += roundTotal; rollDice = "pass"; } } System.out.println ("Computer Total: " + cTotal); System.out.println ("Player total: " + pTotal);
The methods in my PairOfDice class are as follows:
check, which returns true if the face value of both dice is the same, false otherwise
roll, which rolls both the dice to a new value between 1 and 6
.getValue1 and getValue2 return the face value of the first die and the face value of the 2nd die
If I done this correctly, my loop is suppose to end once either the player or computer reach 100 and print the results on screen, but it continues on even after either reaches 100. Can anyone spot the error in this loop as I'm having trouble spotting any flaws in my logic.