Game of Craps constantly looping - java

I am doing a task I was assigned in my Java programming course and I'm quite new to Java. Everything runs fine in the program as long as you don't trigger the do while statement, that's when it starts to loop out of control saying 'You rolled: 7 You lose'.
import java.util.Scanner; //Importing the java.util class Scanner
public class Craps {
private Die die1;
private Die die2;
public Craps() {
die1 = new Die();
die2 = new Die();
}
private void rollDice() {
die1.roll();
die2.roll();
}
private int getSum() {
return die1.getNumber() + die2.getNumber();
}
private int getSum2() {
return die1.getNumber() + die2.getNumber();
}
public void playRound() {
rollDice();
int sum = getSum();
int sum2 = getSum2();
System.out.println("You rolled: " + sum);
if (sum == 7 || sum == 11) {
System.out.println("You Win");
}
if (sum == 2 || sum == 3 || sum == 12) {
System.out.println("You Lose");
} else if (sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10) {
System.out.println("Establishing the point, Re-rolling...");
rollDice();
sum2 = getSum2();
do {
if (sum2 == 7) {
System.out.println("You rolled: " + sum2);
System.out.println("You lose");
}
if (sum2 == sum) {
System.out.println("You rolled: " + sum2);
System.out.println("You win!!!");
}
}
while (sum2 != sum || sum2 != 7);
}
}
public static void main(String[] args) {
Craps game = new Craps();
System.out.println("Welcome to the game of Craps!!!");
System.out.println("Rules: ");
System.out.println("Rolling a 7 or 11 will win you the game");
System.out.println("Subsequently rolling 2, 3, or 12 will lose you the game");
System.out.println("If you roll a 4, 5, 6, 8, or 10 you will 'Establish the point'");
System.out.println("Establishing the point allows you to set a new winning number and reroll");
System.out.println("When you establish the point, the goal is to not roll a 7 and instead roll");
System.out.println("the established number, rolling after establishing a point 7 now will");
System.out.println("result in a loss");
String ans = null;
Scanner scan = new Scanner(System.in);
do {
game.playRound();
ans = scan.nextLine();
}
while (ans.equalsIgnoreCase("Yes"));
}
}
EDIT My Die class
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;
}
}

sum and sum2 are never updated inside your do/while loop, so once you get into the loop, you're never going to get out of it.
do {
if (sum2 == 7) {
System.out.println("You rolled: " + sum2);
System.out.println("You lose");
}
if (sum2 == sum) {
System.out.println("You rolled: " + sum2);
System.out.println("You win!!!");
}
}
while (sum2 != sum || sum2 != 7); // Condition never changes
Another nice pattern is taking advantage of return to short circuit:
while (true) {
rollBabyRoll();
if (getSum2() == 7) {
// Log
return;
else if (getSum() == sum) {
// Log
return;
}
}
Bonus
As another little tip, I don't know Craps at all, but you may want to think about using recursion instead.
private void reroll(int sum) {
rollDice();
int sum2 = getSum2();
if (sum2 == 7) {
// Do something
else if (sum2 = sum) {
// Do something
} else {
reroll(sum);
}
}

Related

GameContinue() not functioning. should loop back to beginning of main()

I am currently creating a pig game, and have most functions working.
I need the code to work where if player 1 decides to stop rolling, and player two decides to stop rolling, the game will loop back until one player reaches 20 points. Currently, the code ends after 1 run through.
import java.util.Random;
import java.util.Scanner;
public class Project3_Part1_Submit {
static int playerScore = 0;
static int playerTotal = 0;
static int dice = 0;
static final int FINAL_SCORE = 20;
static int playerTwoScore = 0;
static int playerTwoTotal = 0;
static boolean gameOver = false;
static boolean turnOver = false;
static char repeat;
static String input;
static Scanner key = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
PlayerOneTurn();
PlayerTwoTurn();
GameContinue();
if (playerTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 1 wins!");
}
if (playerTwoTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 2 wins!");
}
}
public static void PlayerOneTurn() {
while (turnOver == false) {
do {
System.out.print("Player 1 turn total is " + playerTotal); // welcome line
System.out.print(". Enter (r)oll or (s)top: ");
System.out.println("");
input = key.next(); // input = next key entered
repeat = input.charAt(0);
if (repeat == 'r') // if input letter = r
{
dice = rand.nextInt(3) + 1; // set dice to number between 1-6
System.out.println("Player 1 rolled: " + dice); // display number, signifying the amount rolled
if (dice == 1) // if the number rolled happens to be 1...
{
playerScore = 0; // reset score to 0
System.out.print("Player 1 lost their turn! ");
System.out.print("Player 1 total is " + playerTotal);
System.out.println("");
return;
}
else
{
playerScore += dice; // add dice amount to player score
System.out.print("Player 1 turn total is " + playerScore);// print out total amount earned
System.out.print(" Enter (r)oll or (s)top: "); // repeat question
System.out.println("");
input = key.next();
repeat = input.charAt(0);
if (playerScore >= 20) {
playerTotal = playerScore;
gameOver = true;
return;
}
}
}
else if (repeat == 's') // if neither option is called
{
return;
}
else
{
System.out.println("Incorrect entry, please try again"); // prompt retry
System.out.println("");
input = key.next();
}
}while(turnOver == false || dice != 1);
playerTotal += playerScore;
playerScore = 0;
if (playerTotal >= FINAL_SCORE) {
// System.out.println("YOU WIN!");
gameOver = true;
while (playerTotal >= FINAL_SCORE)
;
break;
}
}
}
public static void PlayerTwoTurn() {
System.out.println("success");
while (turnOver == false) {
do {
System.out.print("Player 2 turn total is " + playerTwoTotal); // welcome line
System.out.print(". Enter (r)oll or (s)top: ");
System.out.println("");
input = key.next(); // input = next key entered
repeat = input.charAt(0);
if (repeat == 'r') // if input letter = r
{
dice = rand.nextInt(3) + 1; // set dice to number between 1-6
System.out.println("Player 2 rolled: " + dice); // display number, signifying the amount rolled
System.out.println("");
if (dice == 1) // if the number rolled happens to be 1...
{
playerTwoScore = 0; // reset score to 0
System.out.print("Player 2 lost their turn! ");
System.out.print("Player 2 total is " + playerTwoTotal);
System.out.println("");
return;
}
else
{
playerTwoScore += dice; // add dice amount to player score
System.out.print("Player 2 turn total is " + playerTwoScore);// print out total amount earned
System.out.print(" Enter (r)oll or (s)top: "); // repeat question.
System.out.println("");
input = key.next();
repeat = input.charAt(0);
if (playerTwoScore >= 20) {
playerTwoTotal = playerTwoScore;
gameOver = true;
return;
}
}
}
else if (repeat == 's') // if neither option is called
{
turnOver = true;
return;
}
else
{
System.out.println("Incorrect entry, please try again"); // prompt retry
System.out.println("");
input = key.next();
}
}while(turnOver == false || dice != 1);
playerTwoTotal += playerTwoScore;
playerTwoScore = 0;
if (playerTwoTotal >= FINAL_SCORE) {
// System.out.println("YOU WIN!");
gameOver = true;
while (playerTwoTotal >= FINAL_SCORE)
;
break;
}
}
}
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
PlayerOneTurn(); //go back to playerOne
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
}
My GameContinue() function is what i created to go loop back to PlayerOne.
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
gameOver = false;
PlayerOneTurn(); //go back to playerOne
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
I know calling PlayerOneTurn(); will not loop it back to the start of the main method. I've tried calling all three methods again like this.
public static void GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) { //if neither players totals or 20 or greater
gameOver = false;
PlayerOneTurn(); //go back to playerOne
PlayerTwoTurn();
GameContinue();
}
else //if either one is 20 or greater
{
return; //go to main method and finish
}
}
Obviously that just caused a butload of errors. How should i go about having my code continue to loop back until the if statement in GameContinue() is met?
As Ecto has commented, you could use a while loop in the main function. It is shown here:
public static void main(String[] args) {
while (GameContinue()) {
PlayerOneTurn();
PlayerTwoTurn();
}
if (playerTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 1 wins!");
}
if (playerTwoTotal >= FINAL_SCORE) {
System.out.print("Current Score: Player 1 has " + playerTotal);
System.out.print(", Player 2 has " + playerTwoTotal);
System.out.println("");
System.out.println("Player 2 wins!");
}
}
Now obviously this would be an error as GameContinue() is a void method. To combat this you can change GameContinue() to this:
public static boolean GameContinue() {
if (playerTotal < 20 && playerTwoTotal < 20) {
gameOver = false;
return true;
} else {
return false;
}
}
This would solve your problems and your code is minimally changed.

why is my loop iterating and how do i resolve this?

My code is not stopping the iteration where i use the do while loop, i wanted to only iterate when the secondThrow is not the same as the firstThrow and not a number 7????? help
import java.util.Scanner;
public class Craps_callee
{
private Die die1;
private Die die2;
public Craps_callee() //
{
die1 = new Die ();
die2 = new Die ();
}
private void rollDice()
{
die1.roll();
die2.roll();
}
private int getSum()
{
int sum = die1.getNumber()+die2.getNumber();
return sum;
}
public void playRound()
{
rollDice();
int firstThrow = getSum();
int secondThrow = getSum();
//for (int i; i )
if(firstThrow == 7 || firstThrow == 11)
{
System.out.println("You rolled a " +firstThrow+ " You Win Congratulations!");
}
else if (firstThrow == 2 || firstThrow == 3 || firstThrow == 12)
{
System.out.println("You rolled a "+firstThrow+" You Lose! ");
}
else
{
System.out.println("You rolled a: "+firstThrow);
System.out.println(" !! Establish Point !!");
System.out.println(" you need to roll another "+firstThrow+" to win before 7 is rolled");
do
{
rollDice();
secondThrow = getSum();
System.out.println("SeconndThrow is: "+secondThrow);
System.out.println("FirstThrow is: "+firstThrow);
if (secondThrow == firstThrow)
{
System.out.println("You rolled a " +secondThrow+ " Twice. You Win Congratulations!");
}
else if (secondThrow == 7)
{
System.out.println("You rolled a 7 You Lose! ");
}
}
while (secondThrow != firstThrow || secondThrow != 7);
}
}
public static void main(String[] args)
{
String prompt_from_user;
Scanner scan = new Scanner(System.in);
System.out.println("Input the amount of "+scan);
prompt_from_user = scan.nextLine();
if (prompt_from_user == "YES" || prompt_from_user == "yes");
{
}
This is the part that's wrong
do
{
rollDice();
secondThrow = getSum();
System.out.println("SeconndThrow is: "+secondThrow);
System.out.println("FirstThrow is: "+firstThrow);
if (secondThrow == firstThrow)
{
System.out.println("You rolled a " +secondThrow+ " Twice. You Win Congratulations!");
}
else if (secondThrow == 7)
{
System.out.println("You rolled a 7 You Lose! ");
}
}
while (secondThrow != firstThrow || secondThrow != 7);
I wanted to only iterate when the > secondThrow is not the same as > > the firstThrow and not a number 7
Read the sentence and realise then that your condition should implement an AND instead of an OR

Java classes and calling variables in other classes

I'm still fairly new in java programming and I've gotten some aspects down but the classes within Java are by far giving me the most trouble. What I'm trying to do is make a random number game where the player has to pick a number 1 through 10 and if it's wrong then try again and have the program record how many times they guessed (but not add to the number of guess when a number has been picked previously or if the number that was picked is outside the specified range) I have already worked out the logic code and was trying to make a class specifically for just the logic and a class that is specifically just for the I/O interface. But I'm having one heck of a time. Any input or tips will be very appreciated and I will provide the code that I already have below:
This is the Logic class where I want it to handle all the logic
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessLogic {
public static int Logic() {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
int A;
int guess;
int NumGuess = 1;
do {
guess = keyboard.nextInt();
if (hs.contains(guess)) {
A = 1;
return A;
}
if (guess < 0 || guess > 10) {
A = 2;
return A;
}
if (guess == GuessLogic) {
A = 3;
return A; // this will stop the loop
} else if (guess < GuessLogic) {
NumGuess++;
A = 4;
return A;
} else if (guess > GuessLogic) {
NumGuess++;
A = 5;
return A;
}
hs.add(guess);
} while (true);
}
public static int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
And this is the class I want to handle all I/O interface
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
r = GuessLogic.Logic();
w = GuessLogic.getGuess();
int NumGuess;
NumGuess = 2;
System.out.print("Enter a guess: ");
if (r == 1) {
System.out.println("You have already entered this number");
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
}
}
}
Below is the modified codes. There are some general ideas:
GuessLogic should be used as an instance rather than a static class. Because you need GuessLogic to save the operations and the target number.
The while loop should be coded in main. Because GuessLogic is responsible for logic only.
The elements is Set is unique, so there is no need to count how many different number by yourself.
GuessApp:
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
GuessLogic guessLogic = new GuessLogic();
while(true){
System.out.print("Enter a guess: ");
w = guessLogic.getGuess();
r = guessLogic.Logic();
if (r == 1) {
System.out.println("You have already entered this number");
continue;
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue;
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + guessLogic.getNumber());
break;
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + guessLogic.getNumber());
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + guessLogic.getNumber());
}
}
}
}
GuessLogic:
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int number = (int) (Math.random() * 10 + 1);
public int getNumber(){
return hs.size();
}
public int Logic(int guess) {
if (hs.contains(guess)) {
return 1;
}
if (guess < 0 || guess > 10) {
return 2;
}
if (guess == number) {
return 3; // this will stop the loop
} else if (guess < number) {
// just add to the set. The set will guarantee that there is no repetitive item.
hs.add(guess);
return 4;
} else if (guess > number) {
hs.add(guess);
return 5;
}
return -1;
}
public int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}

I have to create a High Low game. I don't understand why it won't work

public static void main(String[] args) {
int money = 100, roll1, roll2;
int userBet;
char c;
int lostwin;
Scanner in = new Scanner(System.in);
do {
if (money == 0 || money < 0)
break;
System.out.println(" You have " + money + " dollars. ");
userBet = getBet(in, money);
if (userBet == 0)
break;
c = getHighLow(in);
roll1 = getRoll();
System.out.println(" Die 1 rolls : " + roll1);
roll2 = getRoll();
System.out.println(" Die 2 rolls : " + roll2);
System.out.println("Total of two dice is: " + (roll1 + roll2));
lostwin = determineWinnings(c, userBet, roll1 + roll2);
if (lostwin < 0)
System.out.println("You lost!");
else
System.out.println("You won " + lostwin + " dollars! ");
money = money + lostwin;
} while (true);
}
private static int getBet(Scanner inScanner, int moneyPot) {
System.out.println("Enter an amount to bet (0 to quit): ");
int result = inScanner.nextInt();
if (result > moneyPot) {
do {
System.out.println("Enter an amount to bet (0 to quit): ");
result = inScanner.nextInt();
} while (result > moneyPot);
}
return result;
}
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
String str = inScanner.next();
return str.charAt(0);
}
private static int getRoll() {
return (int) (Math.random() * 6) + 1;
}
private static int determineWinnings(char highLow, int bet, int roll) {
int result = 0;
if (highLow == 'H') {
if (roll < 7) {
result = -1 * bet;
} else {
result = bet;
}
}
if (highLow == 'L') {
if (roll > 7) {
result = -1 * bet;
} else {
result = bet;
}
}
if (highLow == 'S') {
if (roll == 7) {
result = 4 * bet;
} else {
result = -1 * bet;
}
}
return result;
}
I need the program to say "Goodbye!" when the user enters the number 0, but I can't figure out where to put it or how to get it to work. The other issue I need help with is if the user enters a number higher than 100 or less than 1, the program needs to say "Your bet MUST be between 0 and 100 dollars". I don't know where to put them or how to get them to work.
You can modify your getBet function like this to achieve what you want.
private static int getBet(Scanner inScanner, int moneyPot) {
int result;
System.out.println("Enter an amount to bet (1-100) (0 to quit): ");
do {
result = inScanner.nextInt();
if (result == 0) {
System.out.println("Good Bye");
return result;
} else if (result < 0 && result > 100) {
System.out.println("Please enter an amount between (1-100) (0 to quit)");
} else if (result > moneyPot) {
System.out.println("Please enter an amount less than your moneyPot between (1-100) (0 to quit)");
} else {
return result;
}
} while (true);
}
public static void main(String[] args) {
int money = 100;
int roll1;
int roll2;
int userBet;
int lostwin;
char c;
Scanner in = new Scanner(System.in);
do {
if (money < 1)
break;
System.out.println(" You have " + money + " dollars. ");
userBet = getBet(in, money);
if (userBet == 0)
break;
c = getHighLow(in);
roll1 = getRoll();
System.out.println(" Die 1 rolls : " + roll1);
roll2 = getRoll();
System.out.println(" Die 2 rolls : " + roll2);
System.out.println("Total of two dice is: " + (roll1 + roll2));
lostwin = determineWinnings(c, userBet, roll1 + roll2);
if (lostwin < 0)
System.out.println("You lost!");
else
System.out.println("You won " + lostwin + " dollars! ");
money = money + lostwin;
} while (money > 0);
System.out.println("Goodbye!");
}
private static int getBet(Scanner inScanner, int moneyPot) {
int bet;
do {
System.out.println("Enter an amount to bet (0 to quit): ");
bet = inScanner.nextInt();
} while (bet > moneyPot && bet != 0);
return bet;
}
private static char getHighLow(Scanner inScanner) {
System.out.println("High, low or sevens (H/L/S): ");
String str = inScanner.next();
return str.charAt(0);
}

Encountering Error with Pig Code

My variable names are pretty stupid near the bottom but that's not the point. Line 110 says that I'm making an else statement without the if and I'm nearly certain the if is there. Please help in any way you can.
Thank you
import java.util.*;
public class hw7
{
public static void main(String[] args)
{
int turnScores = 0;
int totalScores = 0;
int turnScores2 = 0;
int totalScores2 = 0;
int dice;
int dice2;
String input = "r";
char repeat;
boolean peppers;
peppers = true;
Scanner keyboard = new Scanner(System.in);
Random randomNumbers = new Random();
System.out.println("Welcome to the game of Pig!\n");
while(totalScores < 20 || totalScores2 < 20)
{
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScores = 0;
System.out.print("Your lose your turn!");
System.out.println("Your Total is " + totalScores);
break;
}
else
{
turnScores += dice;
System.out.print("Your turn score is " + turnScores);
System.out.println(" and your total scores is " + totalScores);
System.out.println("If you hold, you will have " + turnScores
+ " points.");
System.out.println("Enter 'r' to roll again, 'h' to hold.");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 'h')
{
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
totalScores += turnScores;
peppers = peppers(turnScores, turnScores2);
System.out.println("Your scores is " + totalScores);
turnScores = 0;
System.out.println();
System.out.println("It is the computer's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("The computer rolled: " + dice2);
if(dice2 == 1)
{
turnScores2 = 0;
System.out.print("The computer lost its turn!");
System.out.println(" Computer total is " + totalScores2);
break;
}
else
{
turnScores2 += dice2;
if(turnScores2 >= 20 || (totalScores2 + turnScores2) >= 20 )
{
System.out.println("The computer holds");
break;
}
}
}
while(dice2 != 1 || turnScores2 < 20);
totalScores2 += turnScores2;
System.out.println("The computer's scores is " + totalScores2 + "\n");
turnScores2 = 0;
}
}
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20);
{
done = false;
System.out.println(" YOU WIN!!!");
return done;
}
else (ghost >= 20);
{
done = false;
System.out.println(" COMPUTER WINS");
return done;
}
/*else
{
return done;
}
*/
}
}
Try removing the semicolons in if(chili >= 20); and else (ghost >= 20);.
public static boolean peppers(int chili, int ghost)
{
boolean done;
done = true;
if(chili >= 20)
{
done = false;
System.out.println(" YOU WIN!!!");
}
else if (ghost >= 20)
{
System.out.println(" COMPUTER WINS");
}
return done;
}
replace
else (ghost >= 20);
with
else if (ghost >= 20)
and remove the semicolons after the if-statement.

Categories