Reputation: 3
I am teaching myself Java using Savitch's Absolute Java. I am working on the programming projects: what I am asked to do is code a game of craps. My code works overall, but I am getting an infinite loop with a portion of it. Can anybody points out what I am doing wrong? This is what I am asked to do: If 4, 5, 6, 8, 9, or 10 is rolled on the come out roll, that number becomes “the point.” The player keeps rolling the dice until either 7 or the point is rolled. If the point is rolled first, then the player wins the bet. If a 7 is rolled first, then the player loses.
Here is my code:
import java.util.Random;
public class ProgProject2
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
Random randomGeneratorDice1 = new Random();
Random randomGeneratorDice2 = new Random();
//int counter = 1;
int dice1, dice2, sum, winNumber = 0, lossNumber = 0;
for (int counter = 1; counter <= 3; counter++)
{
System.out.println("Roll number " + counter + " of the dice: ");
dice1 = randomGeneratorDice1.nextInt(6) + 1;
dice2 = randomGeneratorDice2.nextInt(6) + 1;
sum = dice1 + dice2;
System.out.println("Dice1 value is: " + dice1 + " and dice2 value is: "
+ dice2);
System.out.println("The output of the dice roll is: " + sum);
if ((sum == 7) || (sum == 11))
{
System.out.println("You win!!");
winNumber++;
} // end if
else if ((sum == 2) || (sum == 3) || (sum == 12))
{
System.out.println("You lose!!");
lossNumber++;
} // end else if
**else
{
System.out.println("The point!!");
//System.out.println("The sum is: " + sum);
//int point = sum;
int sumElse;
do
{
dice1 = randomGeneratorDice1.nextInt(6) + 1;
dice2 = randomGeneratorDice2.nextInt(6) + 1;
sumElse = dice1 + dice2;
if (sumElse == sum)
{
System.out.println("You win!!");
winNumber++;
} // end inner if
else if (sumElse == 7)
{
System.out.println("You lose!!");
lossNumber++;
} // end inner else
} while ((sumElse != sum) || (sumElse != 7));
} // end else**
} // end for loop
System.out.println("Your total wins are: " + winNumber + " and your total "
+ "losses are: " + lossNumber);
double winProbability = (double) winNumber / (winNumber + lossNumber);
System.out.println("Your winning probability is: " + winProbability);
} // end main
} // end ProgProject2
Upvotes: 0
Views: 79
Reputation: 34146
Change the line
} while ((sumElse != sum) || (sumElse != 7));
to
} while ((sumElse != sum) && (sumElse != 7));
Or you can have an infinite loop, but add break
statements (to exit the loop) in the condition bodies:
do {
dice1 = randomGeneratorDice1.nextInt(6) + 1;
dice2 = randomGeneratorDice2.nextInt(6) + 1;
sumElse = dice1 + dice2;
if (sumElse == sum) {
System.out.println("You win!!");
winNumber++;
break;
} // end inner if
else if (sumElse == 7) {
System.out.println("You lose!!");
lossNumber++;
break;
} // end inner else
} while (true);
Upvotes: 1