So I made quite a few changes to my code and now it complies, but I get the wrong totals and it always thinks Player 2 wins, even before it hits "20". For some reason it isn't reading player 1 totalScore until after player 2 has rolled and then it does not calc player 2 turnTotal. When I made changes before, one thing would start working, but another would stop, so I took it back to where I began to have problems once it would compile.
import java.util.*;
public class Proj3Part1
{
public static void main(String[] args)
{
int turnScore = 0;
int totalScore = 0;
int turnScore2 = 0;
int totalScore2 = 0;
final int WIN = 20;
int dice = 0;
int dice2 = 0;
String input = "r";
String input2 = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Scanner s = new Scanner (System.in);
Random randomNumbers = new Random();
while(totalScore < WIN && totalScore2 < WIN)
{
//Player 1's turn
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScore = 0;
System.out.println("Turn over.");
System.out.println("Player 1 total is " + totalScore);
break;
}
else
{
turnScore += dice;
System.out.print("Player 1 turn total is " + turnScore + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over.");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input.equalsIgnoreCase("r") || dice != 1);
{
totalScore += turnScore;
}
if(totalScore >= WIN)
{
System.out.println("Your total Score is " + totalScore);
System.out.println("Player 1 wins!");
}
//player2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
{ do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("Player 2 rolled: " + dice2);
if(dice2 == 1)
{
turnScore2 = 0;
System.out.print("Turn over");
System.out.println("Player 2 total is " + totalScore2);
break;
}
else
{
turnScore2 += dice2;
System.out.print("Player 2 total is " +turnScore2 + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input2.equalsIgnoreCase("r") && dice != 1); {
totalScore2 += turnScore2;
}
}
if(totalScore2 >= WIN);
{
System.out.println("Player 2 score is " + totalScore2 + "\n");
System.out.println("Player 2 wins");
break;
}
}
}
}
There is an error in the loop for player2/computer's turn. It's in the first if-else loop, located in the else portion.
input keyboard.nextLine();
should be
input = keyboard.nextLine();
It works fine after correcting that error.
Also, pay close attention to the compilation errors, they will point you towards which lines are generating said error.
Revision:
I think this works the way you intended it to.
import java.util.*;
public class Proj3Part1
{
public static void main(String[] args)
{
int turnScore = 0;
int totalScore = 0;
int turnScore2 = 0;
int totalScore2 = 0;
final int WIN = 20;
int dice = 0;
int dice2 = 0;
String input = "r";
String input2 = "r";
char repeat;
Scanner keyboard = new Scanner(System.in);
Scanner s = new Scanner (System.in);
Random randomNumbers = new Random();
while(totalScore < WIN && totalScore2 < WIN)
{
//Player 1's turn
do
{
dice = randomNumbers.nextInt(6) + 1;
System.out.println();
System.out.println("You rolled: " + dice);
if(dice == 1)
{
turnScore = 0;
System.out.println("Turn over.");
System.out.println("Player 1 total is " + totalScore);
break;
}
else
{
turnScore = dice; //removed +=??? think it's only the value of dice roll?
//either way it's used to compute total, which would be redundant if not
totalScore +=turnScore; //added to compute totalScore before turn is over
System.out.print("Player 1 turn total is " + totalScore + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over.");
System.out.print("Current score: Player 1 has " + totalScore); //previously total wasn't computed
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}while(input.equalsIgnoreCase("r"));
//totalScore += turnScore; was removed + curly braces that seemed to attach it to the above while loop
//it isn't needed due to totalScore now being calculated after dice is rolled when !=1(else portion)
if(totalScore >= WIN)
{
System.out.println("Your total Score is " + totalScore);
System.out.println("Player 1 wins!");
break; //added to break the loop if player 1 wins
}
//player2's turn
System.out.println();
System.out.println("It is Player 2's turn.");
do
{
dice2 = randomNumbers.nextInt(6) + 1;
System.out.println("Player 2 rolled: " + dice2);
if(dice2 == 1)
{
turnScore2 = 0;
System.out.print("Turn over");
System.out.println("Player 2 total is " + totalScore2);
break;
}
else
{
turnScore2 = dice2; //removed += ... same as for player 1's turn
totalScore2 += turnScore2; //added totalScore2 calculations.
System.out.print("Player 2 total is " +totalScore2 + " ");
System.out.print("Enter (r)oll or (s)top: ");
input = keyboard.nextLine();
repeat = input.charAt(0);
if(repeat == 's')
{
System.out.println("Turn over");
System.out.print("Current score: Player 1 has " + totalScore);
System.out.println(", Player 2 has " + totalScore2);
break;
}
}
}
while(input2.equalsIgnoreCase("r")); //{ <- incorrect brace + fixed loop for dice2 !=1, then removed it :P since you already did a check inside the do-while loop
//totalScore2 += turnScore2; removed, no longer is needed
//}
//} <- not needed nor is the brace that was infront of the do while loop.
if(totalScore2 >= WIN) //removed semicolon since it ended the if statement before it's body
{
System.out.println("Player 2 score is " + totalScore2 + "\n");
System.out.println("Player 2 wins");
break;
}
if(totalScore>totalScore2) //added loops to check which score is higher and terminate
{
System.out.println("Player 1 Wins!");
break;
}else if(totalScore==totalScore2){
System.out.println("It's a Tie!");
break;
}else if(totalScore<totalScore2){
System.out.println("Player 2 Wins!");
break;
}
}
}
}
I also recommend installing an IDE such as Netbeans or Eclipse. An IDE would make your life much easier, especially with formatting and syntax errors.
Related
I am trying to figure out why I cannot get the loop to break if either "n" is input for playAgain or when the total is below $10. If you see how I can break the loop to run the gameOver function without having an exception thrown that would be a great help. I have noted in the code below that I am having trouble with. I am unsure why this exception is being thrown. If you are able to find out how to break the loop when total is less than 10 or when playAgain is false please let me know!
import java.util.Random;
import java.util.Scanner;
public class GameOfCrapsTester {
static Scanner in = new Scanner(System.in);
static Random rand = new Random();
public static void main(String[] args) {
System.out.println("Welcome to the game of Craps");
System.out.println(" ");
System.out.println("The house has given you a starting balance of $500");
System.out.println("On each round, you will make a whole number wager.");
System.out.println("The minimum wager is $10, and the maximum wager is your remaining balance.");
System.out.println(" ");
System.out.println("You may keep playing until you decide to cash in, or");
System.out.println(" you can't cover the minimum wager.");
System.out.println("Good Luck!");
boolean win;
double wins = 0, numOfGames = 0;
int total = 500;
// Come out roll and set point value
int pointValue = 0;
boolean playAgain = true;
while (playAgain && total > 0)
{
System.out.println(" ");
System.out.println("Your balance is $" + total);
System.out.println(" ");
System.out.println("Place your bet: $");
// Get and check wager placed
int bet = in.nextInt();
while (bet > total || bet < 10)
{
if (bet < 10)
{
System.out.println("Bet must be larger than $10.");
}
System.out.println("I'm sorry, that's not a valid wager; please re-enter: ");
bet = in.nextInt();
}
int num = rollDice();
if ((num >= 4 && num <= 10 && num != 7) || num == 0)
{
pointValue = num;
System.out.println(" ");
System.out.println("Your point value is " + pointValue);
System.out.println(" ");
win = rollWithPoint(pointValue);
if (win)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else if (!win)
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
}
else if (num == 7 || num == 11)
{
total = wonGame(bet, total);
wins++;
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
else
{
total = lostGame(bet, total);
numOfGames++;
System.out.println("Wins: " + wins + " Number of games: " + numOfGames);
}
if (total <= 9) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
System.out.println("Keep playing (y/Y or n/N)? ");
in.nextLine();
String again = in.nextLine();
if (again.equalsIgnoreCase("y"))
{
playAgain = true;
}
else if (again.equalsIgnoreCase("n")) // THIS IS WHERE I AM HAVING TROUBLE
{
break;
}
else
{
System.out.println("Invalid character input, try again:");
again = in.nextLine();
}
}// end of loop
gameOver(wins, numOfGames);
} // END of main
public static int rollDice() {
int dice1, dice2, total;
dice1 = rand.nextInt(6) + 1;
dice2 = rand.nextInt(6) + 1;
total = dice1 + dice2;
System.out.print("Your roll: ");
System.out.print("Dice1: " + dice1);
System.out.print(", Dice2: " + dice2);
System.out.println("; Roll Value: " + total);
return total;
} // END of rollDice
public static boolean rollWithPoint(int point) {
int total = rollDice();
boolean winner = false;
while(total != 7 && winner == false)
{
total = rollDice();
if (total == point)
{
winner = true;
}
else
{
winner = false;
}
}
return winner;
} // END of rollWithPoint
public static int lostGame(int bet, int total) {
System.out.println("Oh, I'm sorry, you lost.");
System.out.println(" ");
total = total - bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of lostGame
public static int wonGame(int bet, int total) {
System.out.println("A winner!");
System.out.println(" ");
total = total + bet;
System.out.println("Your current balance: $" + total);
System.out.println(" ");
return total;
} // END of wonGame
public static void gameOver(double win, double tot) {
double winPercent = (win / tot) * 100;
System.out.println(" ");
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
System.out.println(" ");
System.out.println("Seems you lost your shirt; better luck next time.");
System.out.println("Have a nice day! Hope to see you soon!");
} // END of gameOver
} // END of GameOfCraps
There is no error when you change this (without using String.format()):
System.out.printf("Based on your play, the probability of winning is %.2%", winPercent);
To this:
System.out.println("Based on your play, the probability of winning is " + winPercent + "%.");
Example with a little bet (console):
Your balance is $11
Place your bet: $
10
Your roll: Dice1: 1, Dice2: 2; Roll Value: 3
Oh, I'm sorry, you lost.
Your current balance: $1
Wins: 0.0 Number of games: 2.0
Based on your play, the probability of winning is 0.0%.
Seems you lost your shirt; better luck next time.
Have a nice day! Hope to see you soon!
I cannot get the loop to break if either "n" is input for playAgain or
when the total is below $10.
It works fine too. If I put a bet below 10 it asks me to put another bit. What
I am coding a pig game in Java, and I need help adding up the score. The game's goal is to roll two dice, and the values of those two dice are added together, and the player who gets to 100 first wins. I want to loop the values (which I called "Added") so that it continuously adds up by themselves.
Thank you in advance
By the way, I'm hardly done most of the game, so mind the gaps, lol.
import java.util.Random;
import java.util.Scanner;
public class Pig {
static int player, Continue, roll1, roll2;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
Random r2 = new Random();
System.out.print("Enter 1 to play against computer\nEnter 2 to play against another person\n");
player = keyboard.nextInt();
if (player == 1) {
System.out.println("\nPlaying against the computer...");
roll1 = r.nextInt(6) + 1;
System.out.println("\nYour first roll is a " + roll1);
roll2 = r.nextInt(6) + 1;
System.out.println("\nYour second roll is a " + roll2);
int added = roll1 + roll2;
System.out.println("\nYour total is " + added);
if ((roll1 == 1) || (roll2 == 1)) {
System.out.println("\nYou rolled a 1, you lose all your points!");
}
System.out.print("\nEnter 1 to continue rolling\nEnter 2 to give up the dice\n");
Continue = keyboard.nextInt();
if (Continue == 1) {
do {
roll1 = r.nextInt(6) + 1;
System.out.println("\nYour first roll is a " + roll1);
roll2 = r.nextInt(6) + 1;
System.out.println("\nYour second roll is a " + roll2);
int added2 = roll1 + roll2;
int added3 = added + added2;
added = added2;
added2 = added3;
System.out.println("\nYour total is " + added3);
if ((roll1 == 1) || (roll2 == 1)) {
System.out.println("\nYou rolled a 1, you lose all your points!");
}
System.out.print("\nEnter 1 to continue rolling\nEnter 2 to give up the dice\n");
Continue = keyboard.nextInt();
} while (Continue == 1);
}
} else {
System.out.print("Bye");
}
/*if (player == 2){
System.out.println("Playing against another person...");
}
else {
System.out.print("Bye");
count++;
*/
}
}
I have to write a code for my class I'm taking. It is a game based on betting on 2 colors and numbers from 1 - 36. The user has a set amount of chips already given to them which is 100. I have already written most of the code, however, I can't get my code to repeat the process. I am currently using a Do-While loop. but it just isn't working.
Here is my code:
import java.util.Scanner;
import java.lang.Math;
public class Program_8 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int chipsNow = 100;
int userChoice;
int chipsBetted = 0;
//welcome message
welcome();
do {
int spinNum = (int)(Math.random() * 36) + 0;
userChoice = getMenuChoice(userInput);
//get user choice
if (userChoice == 1) {
int getNum = getNumber(userInput);
int getBet = getBet(userInput, chipsNow);
String determineColor = determineColor(spinNum);
System.out.println("\nSpinning Wheel....");
System.out.println("Spin Number: " + spinNum);
System.out.println("Spin Color: " + determineColor);
if (getNum == spinNum) {
chipsNow += getBet;
chipsBetted += getBet;
System.out.println("Congrats, you won!");
System.out.println("\nYou now have: " + chipsNow + " chips");
;
}
else {
chipsNow -= getBet;
System.out.println("\nSorry, you lost!");
System.out.println("You now have: " + chipsNow + " chips");
}
}
if (userChoice == 2) {
String getColor = getColor(userInput);
int getBet = getBet(userInput, chipsNow);
String determineColor = determineColor(spinNum);
System.out.println("Spinning Wheel....");
System.out.println("Spin Number: " + spinNum);
System.out.println("Spin Color: " + determineColor);
if (getColor.equals(determineColor)) {
chipsNow += getBet;
chipsBetted += getBet;
System.out.println("\nCongrats, you won!");
System.out.println("You now have: " + chipsNow + " chips");
}
else {
chipsNow -= getBet;
System.out.println("\nSorry, you lost!");
System.out.println("You now have: " + chipsNow + " chips");
}
}
}while (userChoice != 3 && chipsNow > 0);
}
//welcome message
public static void welcome() {
int chipsNow = 100;
System.out.println("############################");
System.out.println("# Welcome To Roulette #");
System.out.println("############################");
System.out.println("# Number Bets Payout: 35:1 #");
System.out.println("# Color Bets Payout: 1:1 #");
System.out.println("############################\n");
System.out.println("Chips owned: " + chipsNow + "\n");
System.out.println("1. Pick a number to bet on");
System.out.println("2. Pick a color to bet on");
System.out.println("3. Cash Out\n");
}
//get menu choice
public static int getMenuChoice(Scanner userInput) {
int getMenuChoice;
System.out.println("\nChoose an option [1-3]: ");
getMenuChoice = userInput.nextInt();
return getMenuChoice;
}
public static int getNumber(Scanner userInput) {
int getNumber;
do {
System.out.println("Enter a number to bet on [0-36]: ");
getNumber = userInput.nextInt();
}while (getNumber < 0 || getNumber > 36);
return getNumber;
}
public static String getColor(Scanner userInput) {
String getColor = "";
do{
System.out.println("Enter a color to bet on [Red or Black]: ");
getColor = userInput.next();
}while (!(getColor.equals("Red") || getColor.equals("Black")));
return getColor;
}
public static int getBet(Scanner userInput, int chipsNow) {
int getBet;
do{
System.out.println("Enter the number of chips to bet [1 - " + chipsNow + "]: ");
getBet = userInput.nextInt();
}while (getBet < 1 || getBet > chipsNow);
return getBet;
}
public static String determineColor(int spinNum) {
if (spinNum % 2 == 0) {
if (spinNum == 0) {
return "Green";
}
//even
else {
return "Red";
}
}
return "Black";
}
public static void report(int chipsNow) {
System.out.println("\nThanks for Playing!");
System.out.println("You Won a total of: " + chipsNow + " chips today");
}
}
So just looking at the code I'd:
Declare int userChoice = 0; outside the do while. This is needed for the while condition to work.
welcome(); and userChoice = getMenuChoice(userInput); should move into the do while thus it will repeat the welcome message and ask for a user choice everything the do while executes
Simplify your while loop like this while(userChoice != 3 && chipsNow > 0). This is just to make it more readable.
Lastly remove the break;s in your if(getNum == spinNum) { } else { }. A break will force the while loop to be exited regardless of whether the while condition is met. So basically if you win or lose a game your loop will exit, which I don't think is what you want. You only want the loop to exit if the chipsNow < 0 or the userChoice == 3
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.
Ok, so I have created the following program. It is not yet complete but when the code comes to the end (y or n part) and the user decides to try again they don't get the option to enter a new bet it just uses the one entered from the first time.
(Please comment if you need help about understanding the code or thinking it might be hard for other people to understand)
import java.util.*;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; //variable to cancel whole loop
char yesNo; //if user wants to continue playing or not
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
do { //loop to test if the bet is legit
if(money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while(bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n)");
yesNo = kin.next().charAt(0);
int loopBreak = 0; //to break do while loop bellow
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while(loopBreak == 0);
if(play == 0) {
break;
}
}
}
}
}
Its all about nested while loop don't stop when it needed. Its like this
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
...
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while(loopBreak == 0);
if(play == 0) {
break;
}
}
}
After you get answer 'y' you don't break the nested while and program never get the
while(money > 0 && play == 1) {
--> System.out.print("Please Enter The Amount You Want To Bet: ");
--> double bet = kin.nextDouble();
//because below while loop continues to loop
while((bet <= money || bet > 0)) {
...
}
}
part. Anyways corrected code is here(i tried every possibility and it worked)
import java.util.*;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; //variable to cancel whole loop
char yesNo; //if user wants to continue playing or not
while(money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while((bet <= money || bet > 0)) {
do { //loop to test if the bet is legit
if(money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while(bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n): ");
yesNo = kin.next().charAt(0);
int loopBreak = 0; //to break do while loop bellow
do {
if(yesNo == 'y') { //take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak++;
continue;
}
else if(yesNo == 'n') {
System.out.println("Thank You For Playing");
play--; //to cancel whole program
break;
}
else {
System.out.println("Please Enter 'y' Or 'n': ");
}
} while(loopBreak == 0);
if(play == 0 || loopBreak == 1) {
break;
}
}
}
}
}
Have a good day!
Another solution is to use labeled breaks/continues https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
However it should be used sparingly (or not at all). You probably can simplify it in some other way.
package test.test;
import java.util.Scanner;
public class Lab15 {
static Scanner kin = new Scanner(System.in);
public static void main(String[] args) {
double money = 1000;
System.out.println("Welcom To Craps You Start With 1000$!!!");
int play = 1; // variable to cancel whole loop
char yesNo; // if user wants to continue playing or not
//Labeled <-----------------
start: while (money > 0 && play == 1) {
System.out.print("Please Enter The Amount You Want To Bet: ");
double bet = kin.nextDouble();
while ((bet <= money || bet > 0)) {
do { // loop to test if the bet is legit
if (money < bet || bet < 0) {
System.out.print("Sorry Invalid Bet; Please Enter A Legitimant Bet: ");
bet = kin.nextDouble();
}
} while (bet > money || bet < 0);
money -= bet;
System.out.println("You Have Bet $" + bet + " And Have " + money + " Left");
int die1 = (1 + (int) (6 * Math.random()));
int die2 = (1 + (int) (3 * Math.random()));
int sum = die1 + die2;
System.out.println("You Rolled " + die1 + " and " + die2 + " totaling " + sum);
System.out.print("Do You Want To Play Again(y) Or Not(n)");
yesNo = kin.next().charAt(0);
int loopBreak = 0; // to break do while loop bellow
do {
if (yesNo == 'y') { // take above yes no to restart loop or not
System.out.println("Restarting...");
loopBreak += 1;
//Labeled continue <-----------------
continue start;
} else if (yesNo == 'n') {
System.out.println("Thank You For Playing");
play -= 1; // to cancel whole program
break;
} else {
System.out.println("Please Enter 'y' Or 'n'");
}
} while (loopBreak == 0);
if (play == 0) {
break;
}
}
}
}
}