User inputs integer value for gamblers starting bankroll
User inputs integer value for gamblers desired bankroll – if the gambler’s bankroll reaches this value he quits the game
User inputs integer value for the number of trials to perform – each trial will consist of enough games to either reduce the gamblers bankroll to zero or increase it to the desired bankroll
Declare an integer variable (set to zero) to keep track of the number of wins
The solution, obviously, will consist of nested looping structures and selection structures
First (outer loop) will loop to perform the required number of trials
Set cash equal to stake
Second (inner loop) will simulate the results of one card game. This loop will repeat as long as cash is greater than zero and less than the desired bankroll
Assume that the gambler has chance of winning the game of less than 50%
Use a random number generator to determine if the gambler won the game
If the gambler won, add $1.00 to his cash
Otherwise subtract $1.00 from his cash
At the end of the inner loop (one game is run) -
If the value of cash equals the gamblers desired bankroll, then increment wins by one
After the outer loop stops, print to the screen the number of wins out of the number of trials and the percent of games won.
trying to get a game simulator to count the number of games won after the total starting amount reaches the end amount. part of it works but not all of it
then it should do that x number of times. https://github.com/samuelatlas/gamesimulation/tree/master
'''
// demonstrating the Java for loop
import java.util.Scanner; // import a scanner c
import java.security.SecureRandom; // imports a secure random class
class newLoopTest1
{
public static void main(String[] args)
{
// OUTER -------LOOP
Scanner input = new Scanner(System.in);
System.out.print("Enter the start bankroll ");
int startBankRoll = input.nextInt();
//int desiredBankRoll = 5;
System.out.print("Enter the desired bankroll ");
int desiredBankRoll = input.nextInt();
System.out.print("Enter the number of trials ");
int numberTrials = input.nextInt();
//int startBankRoll = 2;
int i = 1;
int current = startBankRoll;
int wins = 0;
//int numberTrials = 0;
//OUTER----LOOP
while(i <= numberTrials)
//while(numberTrials <= 4)
{
i++;
int innerloop = 0;
System.out.println("printing from outer");
//INNER----LOOP
while((startBankRoll < desiredBankRoll) && (startBankRoll > 0))
{
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
System.out.println("Before hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
System.out.println("Rolled " + number);
if( number <= 50)
{
System.out.println("lost");
startBankRoll--;
System.out.println("After hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
}
else
{
System.out.println("won");
startBankRoll++;
System.out.println("After hand start amount of " +
startBankRoll + " end amount of " + desiredBankRoll);
}
System.out.println(" Outerloop ran " + numberTrials + "
Innerloop ran " + innerloop);
innerloop++;
//INNER----LOOP
}
//OUTER----LOOP
numberTrials += 1;
//wins++;
System.out.println("Current" + current);
if(startBankRoll == desiredBankRoll)
{
wins += 1;
startBankRoll = current;
System.out.println("wins" + wins);
}
else
{
startBankRoll = current;
System.out.println(" lost all cash");
}
//OUTER----LOOP
}
int totalWins = (wins/(numberTrials-1));
System.out.println("Won " + wins + " out of " + (numberTrials-1));
//System.out.println("total percent" + wins/totalWins );
}
}
The main problem with your code seems to lie with understanding the problem. I took at look at the Github page you linked (I noticed your assignment is due tomorrow -- please do not wait until the last minute to ask for help in the future, and always ask the teacher first, rather than some stranger on Stack Overflow). Let's break down the assignment properly.
The player starts with cash (in your case, 2 units), so we know how to initialize startCash, which you've done properly
His goal is to get to 10 units or bust, so we know the upper and lower limits that define the parameters for his participation in the game. In other words, he only plays while he has > 0 and < 10 units. An outer loop checking to see if he has enough cash is pointless.
While those conditions are true, he plays a coin flipping game, where 50 or less is a loss of one unit and 51 or more is a win of one unit. Each time he flips, we increment a counter so we know how many coin flips he conducted to get to either 0 or 10.
Notice how I've rephrased the question: While cash > 0 and cash < 10, flip coin. If flip < 50, player loss, else win. Increment counter. That's all there is to it, all in one loop.
You confused yourself by adding an outer loop which you don't need at all -- maybe you put it there to keep flipping while the player has money, but it's redundant because your do...while is checking both the lower and upper limits for whether the game should be played. That outer loop is also running 5 times, but what if it takes more than 5 trials to bust or get 10?
I've simplified the code here by basically rearranging what you already had. Compare what you have to what I have and you'll see that I more or less just stripped away the useless outer loop. Run the code a few times and you'll see that you already had more or less the correct logic before you shot yourself in the foot.
import java.security.SecureRandom;
public class Homework
{
public static void main(String[] args)
{
int startCash = 2;
int endCash = 10;
int currentCash = startCash;
int counter = 0;
while(currentCash > 0 && currentCash < endCash)
{
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
if(number <= 50)
{
// lost
currentCash--;
}
else
{
// won
currentCash++;
}
counter++;
}
System.out.println("Current Cash: " + currentCash);
System.out.println("Trials: " + counter);
}
}
The only "major" change other than removing the extra loop is changing your do...while into a while loop. The difference is that a do...while will always run at least once because the exit condition isn't checked until after the code block runs, which doesn't seem correct because what if startCash is already 0 or 10? The while loop checks the condition before running the code block, so if the player is ineligible to play (too much or too little cash), then he doesn't play.
well i figured it all out just took a while and lots of versions. here is the final code. most of the earlier code was to see where the numbers where going.
{import java.util.Scanner; // import a scanner class.
import java.security.SecureRandom; // imports a secure random class.
class TheGambler
public static void main(String[] args)
{
// OUTER -------LOOP AREA
// create scanner for object.
Scanner input = new Scanner(System.in);
//prompt users for the starting bankroll amount.
System.out.print("Enter the start bankroll ");
int startBankRoll = input.nextInt();
//prompt users for the desired bank roll amount.
System.out.print("Enter the desired bankroll ");
int desiredBankRoll = input.nextInt();
//prompt users for the number of tirals.
System.out.print("Enter the number of trials ");
int aNumber = input.nextInt();
//to reset the value after to inner loop has ran.
int current = startBankRoll;
// keep track of number of wins.
int wins = 0;
// keep track of numberTrials.
int numberTrials = 1;
//OUTER----LOOP AREA
//condition for the outer while loop to continue.
while(numberTrials <= aNumber)
{
// number of time inner loops executes.
int innerloop = 0;
//INNER----LOOP
// condition for the inner while loop to continue.
while((startBankRoll < desiredBankRoll) && (startBankRoll > 0))
{
//create a random number and assign it an integer named number.
SecureRandom randomNumber = new SecureRandom();
int number = randomNumber.nextInt(101);
//condition to determine if player wins or a losses.
if( number <= 50)
{
// if losses subtract one from startamount.
startBankRoll--;
}
else
{
// if wins adds one to startamount.
startBankRoll++;
}
// add one to the inner loop count.
innerloop++;
//INNER----LOOP AREA
}
//OUTER----LOOP AREA
//add to the total number of trials ran
numberTrials += 1;
// condition to add one to wins if startamount is equal to desiredamount.
if(startBankRoll == desiredBankRoll)
{
// adds one to the wins count and resets the startamount.
wins += 1;
startBankRoll = current;
}
else
{
//if startamount equals zero reset the startamount.
startBankRoll = current;
}
//OUTER----LOOP AREA
}
// determine total number of games played.
int total = (numberTrials-1);
// converts the amount of wins to a percent.
int percent = wins * 100 / total;
//displays how many wins out of total amount of games played.
System.out.println("Won " + wins + " out of " + total);
//displayes the percent of games won.
System.out.println(percent + "%");
}
}
Related
I just started learning java so I may not even be on the right track but I have an assignment that asks me to create a game of 21. The way the game works is that a player and computer take turns entering either a 1, 2, or 3. The player that enters a number that meets or exceeds 21 loses. The trouble I seem to be having is that I cannot seem to get the program to exit the loop when the final number is entered and it will display that the player loses every time, win or lose.
I have tried using another if statement after the do-while loop to display either "You Win!" or "You Lost." However, I can't figure out what parameters I should use in the if statement to decide who won. I also tried to set the game up with the player as even numbers and the computer as odd numbers but I couldn't get the numbers to add to a running total to end the loop.
int numLoops = 0;
int firstCheck;
int points;
Scanner input = new Scanner(System.in);
do
{
System.out.print("\nEnter a 1, 2, or 3 >> ");
points = input.nextInt();
int random = (int )(Math.random() * 3 + 1);
numLoops = points + numLoops + random;
if(numLoops < 21)
{
System.out.println("The computer entered a " + random);
System.out.println("The new total is " + numLoops);
}
else
{
//This is what always prints.
System.out.println("You lost! The computer is the victor.");
}
}while(numLoops < 21);
//this is what I am having most of my trouble with.
System.out.println("You Win!");
I expect that the loop will close after the total reaches 21 and will output a statement That varies based on who won. However, the program always outputs that the player lost.
If have made a few changes to simplify things. Have a look at the source code, it should be well documented and explains things best.
/*
* Which players turn is it?
* (true for human player, false for computer)
*/
boolean isHumanPlayersTurn = true;
int totalPoints = 0;
Scanner input = new Scanner(System.in);
// the game ending condition
while (totalPoints < 21) {
// take an action, depending on the players turn
if (isHumanPlayersTurn) {
System.out.print("\nEnter a 1, 2, or 3 >> ");
totalPoints += input.nextInt();
} else {
int random = (int) (Math.random() * 3 + 1);
System.out.println("The computer takes " + random);
totalPoints += random;
}
System.out.println("Total amount is " + totalPoints);
/*
* Important part: After each players move, change the players turn, but do NOT
* do this if the game already ended, since then the other player would have won.
*/
if (totalPoints < 21) {
isHumanPlayersTurn = !isHumanPlayersTurn;
}
}
// now, the player to move is the one who loses
if (isHumanPlayersTurn) {
System.out.println("You lost! The computer is the victor.");
} else {
System.out.println("You Win!");
}
After the user enters a number, you should check immediately to see if they hit 21 (and also output the total at that point). If 21 was not hit, then the computer should guess, and then you check again to see if 21 was hit. So you'll have two if statements (one after each guess; user/computer). In the else block after the user guess is where the computer would guess. Your if statement will check for >= 21, indicating a loss for the user or computer as appropriate. You won't need to declare a victor outside of the loop as this can be done inside the loop...
For example:
int total = 0;
do
{
System.out.print("\nEnter a 1, 2, or 3 >> ");
points = input.nextInt();
total = total + points;
System.out.println("The new total is " + total);
if (total >=21)
{
System.out.println("You lost! The computer is the victor.");
}
else
{
int random = (int )(Math.random() * 3 + 1);
total = total + random;
System.out.println("The computer entered a " + random);
System.out.println("The new total is " + total);
if(total >= 21)
{
System.out.println("You Win!");
}
}
}while(total < 21);
I'm creating a guessing game in Java using NetBeans. The guessing game allows the user to guess a number between 1 and 10. Each round they have 5 chances to guess the number. There are three rounds in the game. After the user finishes the game, stats are outputted with the minimum # of guess and maximum # of guesses.
The minimum guesses isn't working and it always outputs 1. Right now, I have the program set up so that it keeps track of how many times the user guesses per round. After each round, it compares this value to the min value and max value. The minGuess is set as 5 since it isn't possible to guess more than 5 times. The maxGuess is set as 1 since they will always guess one time or more than one time.
static void numberGuess(int guess, int randNum) { //creating a method to check if the user has guessed the correct number or if the guess should be higher or lower
if (guess < 0 | guess > 10) {
System.out.println("Please enter a valid number between 1 and 10.");
}
else if (guess == randNum) {
System.out.println("You guessed the number correctly");
}
else if (guess < randNum) {
System.out.println("Guess is too low");
}
else if (guess > randNum) {
System.out.println("Guess is too high");
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
/*Rational: This program allows a user to guess a number between 1 and 10 five times per round. There are three rounds in one game.
The program then outputs the stats for the game.
*/
//declaration
int userGuess; //creates a spot in memory for these variables
int numOfGuess = 0;
int invalidGuess = 0;
int minGuess = 5;
int maxGuess = 1;
int average;
Scanner Input = new Scanner (System.in); //creates an object in the scanner clas
//execution
System.out.println("Welcome to Super Guessing Game! Guess a random number between 1 and 10. There are three rounds with one guess each.");
loopOne: //labels the loop as loopTwo
for (int x = 1; x <= 3; x= x + 1 ) { //runs the loop for three rounds
System.out.println(" ");
System.out.println("Round " + x);
System.out.println("To exit the game at any point, enter a negative 1");
System.out.println(" ");
int randNum;
randNum = 1 + (int)(Math.random() * ((10 - 1) + 1)); //generates the random number
loopTwo: //labels the loop as loopTwo
for (int y = 1; y <= 5; y= y + 1) { //runs the loop five times (five guesses per round)
numOfGuess = numOfGuess + 1; //counts number of guesses user has made
System.out.println("Guess " + y + " out of 5");
System.out.println("Please guess a number between 1 and 10: ");
userGuess = Input.nextInt();
if (userGuess == -1){ //sentinel to let the user quit at any time
System.out.println("Thank you for playing");
break loopOne; //breaks out of the loops if the user wants to stop playing
}
numberGuess(userGuess, randNum); //calls the numberGuess method
if (y < minGuess) //compares to see if the minimum number of guesses is less that the number of guesses the user has made this round
minGuess = y;
if (y > maxGuess) //compares to see if the maximum number of guesses is greater than the number of guesses that the user has made this round
maxGuess = y;
if (userGuess <1 | userGuess > 10) { //keeps track of invalid guesses
invalidGuess = invalidGuess + 1;
}
if (userGuess == randNum) { //exits the round if the user guesses correctly
break;
}
}
}
average = numOfGuess / 3; //calculates the average number of guesses
System.out.println("Thanks for playing!"); //outputs the following
System.out.println("");
System.out.println("Number of Guesses Made: " + numOfGuess);
System.out.println("Average Number of Guesses: " + average);
System.out.println("Number of Invalid Guesses: " + invalidGuess);
System.out.println("Minimum Guesses Used: " + minGuess);
System.out.println("Maximum Guesses Used: " + maxGuess);
}
}
y starts at one, and is never less than one, thus minGuess is always one.
for (int y = 1; y <= 5; y= y + 1) {
...
if (y < minGuess)
minGuess = y;
...
}
Consider only updating minGuess and maxGuess upon a successful guess.
Your if statement is at the wrong place.
Your asking every time. also if the user isnt guessing the right number.
so just put it in ur numberguess method:
else if (guess == randNum) {
System.out.println("You guessed the number correctly");
if (y < minGuess) //compares to see if the minimum number of guesses is less that the number of guesses the user has made this round
minGuess = y;
if (y > maxGuess) //compares to see if the maximum number of guesses is greater than the number of guesses that the user has made this round
maxGuess = y;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Whenever I execute the program the average change always is 0 and I do not understand why.
/*LuckySevens.java
Simulate the game of lucky sevens until all funds are depleted.
1) Rules:
roll two dice
if the sum equals 7, win $4, else lose $1
2) The inputs are:
the amount of money the user is prepared to lose
3) Computations:
use the random number generator to simulate rolling the dice
loop until the funds are depleted
count the number of rolls
keep track of the maximum amount
4) The outputs are:
the number of rolls it takes to deplete the funds
the maximum amount
the average net change after 100 rolls
*/
import java.util.Scanner;
import java.util.Random;
public class LuckySevens {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
Random generator = new Random();
int die1, die2, // two dice
dollars, // initial number of dollars (input)
countAtMax, // count when the maximum is achieved
count, // number of rolls to reach depletion
maxDollars, // maximum amount held by the gambler
averageWin, // the average net change after 100 rolls
initialDollars; // initial amount of money user has
// Request the input
System.out.print("How many dollars do you have? ");
dollars = reader.nextInt();
// Initialize variables
maxDollars = dollars;
initialDollars = dollars;
countAtMax = 0;
count = 0;
// Loop until the money is gone
while (dollars > 0){
count++;
// Roll the dice.
die1 = generator.nextInt (6) + 1; // 1-6
die2 = generator.nextInt (6) + 1; // 1-6
// Calculate the winnings or losses
if (die1 + die2 == 7)
dollars += 4;
else
dollars -= 1;
// If this is a new maximum, remember it
if (dollars > maxDollars){
maxDollars = dollars;
countAtMax = count;
}
/* TODO:FIX BELOW STATEMENT
it always returns influx as 0 */
if (count == 100) {
averageWin = ((maxDollars - initialDollars) / 100);
System.out.println ("In the first 100 rolls there an average money influx of " + averageWin + " per roll.") ;
}
}
// Display the results
System.out.println
("You went broke after " + count + " rolls.\n" +
"You should have quit after " + countAtMax +
" rolls when you had $" + maxDollars + ".");
}
}
Make averageWin as double variable.
Change calculation of average win as below
averageWin = ((double)maxDollars - (double)initialDollars) / 100;
I tried the following to get the correct answer.
Changed type of averageWin
double averageWin;
And then calculation formula to
averageWin = (maxDollars - dollars) / 100.0;
This will preserve the precision and give you the correct answer.
I'm having some troubles getting this code to look neat since there are som many IF & OR statement that needs to be evaulated.
Idea: You throw five dices and pick out e.g. three of the same type 1,1,1 and throw dice the other two again and go gather points.
The tricky thing is to compare dice1,dice2,dice3,dice4,dice5 with the set of rules in order to determine how many points the player get. What code would check all the possible combination "if dicex=1 & dicex=1 & dicex=1" give player 1000 points?
int player1points = 0;
int player2points = 0;
Scanner in = new Scanner(System.in);
Random n1 = new Random();
int dice1 = n1.nextInt(6) + 1;
int dice2 = n1.nextInt(6) + 1;
System.out.println("Dice 1 shows " +dice1);
System.out.println("Dice 2 shows " +dice2);
System.out.println("Dice 3 shows " +dice3);
System.out.println("Dice 4 shows " +dice4);
System.out.println("Dice 5 shows " +dice5);
if /* 1+1+1+1+1 = 2000 */ (dice1==1&&dice2==1&&dice3==1&&dice4==1&&dice5==1){
System.out.println("You got 2000 points! Throw again?");
int points2000 = 2000;
player1points = player1points + points2000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
else if /* 1+1+1 = 1000 */ (dice1==1&&dice2==1&&dice3==1||dice2==1&&dice3==1&&dice4==1||dice3==1&&dice4==1&&dice5==1|| dice4==1&&dice5==1&&dice1==1||dice5==1&&dice1==1&&dice2==1||dice1==1&&dice2==1&&dice4==1||d ice2==1&&dice3==1&&dice5==1||dice3==1&&dice4==1&&dice1==1||dice4==1&&dice5==1&&dice1==1||dice1==1&&dice3==1&&dice5==1){
System.out.println("You got 1000 points!");
int points1000 = 1000;
player1points = player1points + points1000;
System.out.print("You have ");
System.out.print(player1points);
System.out.print(" points. Do you want to throw again?");
System.out.println("Yes/No?");
s = in.nextLine();
}
Put the results of the rolls into an arrayList, then just count the number of times the same number shows up in that array list? If there are 3 1's, give 1000 points, else if there are 5 1's give 2000 points.
So for your code you'll have the same beginning for the most part. Add in methods to populate the array list, and to iterate though/count the results of the dice rolls and return the most common and the number of times it shows up.
int player1points = 0;
int player2points = 0;
int count = 0;
int mostCommon = 0;
int maxCount = 0;
ArrayList<Integer> diceRolls = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
Random n1 = new Random();
//rollDice method (parameter would be number of dice to roll)
//checkResults method (count number of times each number 1-6 shows up)
if(maxCount == 3){
player1points += 1000;
//re-roll 2 dice if necessary
else if(maxCount == 5){
player2points += 2000;
//re-roll dice if wanted
That's just one way you could do it. Also it's always good practice to break big blocks of code down into more reader-friendly functions, and it makes debugging easier! If you need anymore help feel free to ask!
So I'm trying to make a program where it averages out your golf scores. I edited a standard averaging calculator to make it work:
import java.util.Scanner;
public class Test {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int total = 0;
int score;
int average;
int counter = 0;
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
average= total/10;
System.out.println("Your average score is "+ average);
}
}
But when I enter scores, I can keep entering infinite scores and it never averages them. It just keeps expecting another score. I know it has something to do with this line:
while (counter >= 0){
but I'm not sure what to do so it works right.
You never find a way to break out of the loop:
while (counter >= 0){
score = input.nextInt();
total = total + score;
counter++;
}
will loop 2 billion times (no I'm not exaggerating) since you don't have another way to break out.
What you probably want is to change your loop condition to this:
int score = 0;
while (score >= 0){
This will break out when a negative score is entered.
Also, you have an integer division at the end. You want to make floating-point, so change the declaration to this:
double average;
and change this line to this:
average = (double)total / 10.;
You need some way to beak out of the loop. For example, entering -1:
int score = input.nextInt();
if (score < 0) { break; }
total += score;
You also seem to have a couple of errors in the calculation of the average:
Don't always divide by 10 - use the value of counter.
Use floating point arithmetic. If you need an int, you probably want to round to nearest rather than truncate.
For example:
float average = total / (float)counter;
You have to specify the counter value, the default value is 0, so the condition in the while is always true, so you will go in an infinite loop.
while (true) {
score = input.nextInt();
if (score == 0) {
break;
}
total = total + score;
counter++;
}
Now your program will realize you're done entering scores when you enter the impossible score 0.