Lucky Sevens [Net Change Calculation] [closed] - java

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.

Related

having a problem with java for game simulation

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 + "%");
}
}

How do I use an if statement to know whether the player or the computer won?

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);

Java - Least number of bills and coins for change

I have to do an assignment for my class that allows the user to key in two amounts - the first should be the total sale amount and the next would be the amount of change handed to the cashier. The program needs to calculate the change needed and tell the cashier how many of each monetary amount to return to the customer using the least number of bills and coins. Using $20, 10, 5, 1 and 0.25, 0.10, 0.05, and 0.01. I also need to include a while loop to make sure the cashier is given an amount greater than the amount due.
I have the following so far, but don't know where to go from here:
public class Change {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Enter sale amount less than $100
System.out.println("Enter the sale amount: ");
double price = input.nextDouble();
//Enter amount of money handed to cashier less than $100
System.out.println("Enter the amount of money handed to the cashier: ");
double payment = input.nextDouble();
double difference = payment - price;
int num20 = (int)(difference / 20);
System.out.println("num20 = " + num20);
difference = difference % 20;
System.out.println("difference = " + difference);
int num10 = (int)(difference / 10);
System.out.println("num20 = " + num10);
difference = difference % 10;
System.out.println("difference = " + difference);
int numQtr = (int)(difference / .25);
System.out.println("numqtr = " + numQtr);
int numDime = (int)(difference / .10);
System.out.println("numDime = " + numDime);
}
Use the mod operator and division to find values at each step
29 % 20 -> 9
(int) (29 / 20) -> 1
9 % 10 -> 9
(int) (9 / 10) -> 0
please note that casting the result of a division to an integer will truncate the returned value to a whole number.

Dice roll combinations java

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!

Java code, arithmetic and if/else statement issue [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Hoping someone can give me a hand with this code. The beginning of the code you will see my psudo which states what I'm attempting to do. Only ever written in C++ before so the conversion is throwing me off some.
package correctFare;
/* create static variables for figures that will remain constant throughout program (fare,dollar value etc.)
*
* create variable that will be used to store the amount of money the user states is entered (entered amount must be 0=<x<=20
* Prompt user to enter the amount of money they are inserting which will be stored in the input var.
* note* remind user that amount must be divisable by .25 and no greater than 20.0
*
* subtract 2.25 from input, if the input-fare is not >= zero report error insufficient funds
* divide input by 0.25, if the number is not a whole number, int, report error and state that all values bust be multiples of 25 cents
*
* create open double variable as 'change'
* take input, subtract 2.25 and store new amount as change
*
* change is then divided by static variable ten, if zero continue to next step, else store amount as tenChange, change-(tenChange*10) continue to next step
* follow with dividing change by 5, same steps as prior
* repeat again with one
* lastly finish with quarters
*
* Prompt user with total cost of fare, amount entered and then tendered cash broken into each denomination
*/
import java.util.Scanner;
public class CTAFare {
/**
* #param args
*/
static double fare=2.25; //fare amount, remains easily accessible
static double quarter=0.25; //denomination amounts stored as static variables
static int oneDollar=1;
static int fiveDollar=5;
static int tenDollar=10;
static int twentyDollar=20;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner( System.in );
int max = 20;
int min = 0;
double inputAmount;
System.out.println("Please enter the amount of money you wish to insert:");
System.out.println("\n *Please note, this machine will accept bills no larger than $20 and must be divisible by $0.25.");
inputAmount = in.nextDouble();
if (min <= inputAmount <= max)
{
System.out.println("You entered: $"+ inputAmount);
}
else if (max < inputAmount < min)
{
System.out.println("The amount you entered is not acceptable.");
}
double change;
int tenChange;
int fiveChange;
int oneChange;
int quarterChange;
inputAmount-fare = change;
if (change/tenDollar > 0) {
change/tenDollar = tenChange;
change - (tenChange*10) = change;
}
else if (change/fiveDollar > 0) {
change/five = fiveChange;
change - (fiveChange * 5) = change;
}
else if (change/oneDollar > 0) {
change/onDollar = oneChange;
change - (oneChange * 1) = change;
}
else if (change/quarter > 0) {
change/quarter = quarterChange;
change - (quarter*0.25) = change;
}
System.out.println("You have purchased one fare at $"+ fare".\n");
System.out.println("Amount insterted: $"+ inputAmount "\n");
System.out.println("Change tendered: \n");
System.out.println("Ten Dollar Bills: "+ tenChange " \n");
System.out.println("Five Dollar Bills: "+ fiveChange " \n");
System.out.println("One Dollar Bills: "+ oneChange " \n");
System.out.println("Quarters: "+ quarterChange " \n");
}
}
Assignments in C++ are done from right to left, and I'm assuming that's similar for Java. Try changing your assignments...
change/five = fiveChange;
should be
fiveChange = change/five;
In this example, too, you haven't defined what five is anywhere. Unlike in Python, you need to define your variables before or when you use them.
Also, you might want to consider what each type is. I'm not sure int is the best choice in some of your circumstances. Try fixing your assignments and declarations, then see if your output is correct.
This could be a problem I noticed
if (min <= inputAmount <= max)
try using
if (min <= inputAmount && inputAmount <= max)
Here is another mistake
change/five = fiveChange;
You cant do this. Try following
double newFiveCHange = change/five ;
or interchang them like
fiveChange = change/five;
Following are useful links you can use.
1. Summary of Operators
2. The if-then and if-then-else Statements
3. Expressions, Statements, and Blocks
Just replace :
if (min <= inputAmount <= max)
by
if (min <= inputAmount && inputAmount <= max)
and replace :
else if (max < inputAmount < min)
by
else

Categories

Resources