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!
Related
I'm new to programming and trying to make a dice game. The game consists of three dice and involves the sum of 12 (on any number of dice) in each round. Each dice can only be rolled once per round.
In each round, the player must be able to choose between: 1 to roll the dice 1, 2 to roll the dice 2, 3 to roll the dice 3, q to exit the game. The program must randomly find a value on the selected dice and then calculate the score. The program should also present the number of wins and the number of rounds lost. The program should continue until the user chooses to cancel the game. Regardless of the number of dice, and the definition of loss is a sum exceeding 12 after all three dice have been rolled. If the sum after three rolls is less than 12, there will be no profit or loss, but you go straight to the next round.
So currently my code works for 1 round, the problem begins when the second round begins. The new dice rolls are just the input I give it, and not a random value (1-6).
How can I make this work?
import java.util.Scanner;
import java.util.Random;
public class Main{
//Declaring int variables for all 3 dice
static int dice1;
static int dice2;
static int dice3;
//Declaring true/false for which dice that is thrown, can't be thrown more than 1 time in each round.
static boolean dice1Thrown = false;
static boolean dice2Thrown = false;
static boolean dice3Thrown = false;
//Method for which dice is thrown - the input the user choses (1, 2, 3 or q)
static char diceToThrow;
//Method that checks what number 1-6 the dice roll. sum by default is 0
static int sum = 0;
//Method for keep track of # wins
static int wins;
//Method keep tracks of # losses
static int losses;
//If firstGame = true it will print "Welcome to the game 12" if false, it doesn't print that every round
static boolean firstGame = true;
//Int for keeping track of when dice thrown is = 3. Go to next round.
static int rounds;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if(firstGame)
{
System.out.println("Welcome to the game 12. You must roll 1-3 dice and try to get the sum 12 ... ");
firstGame = false;
}
System.out.printf("Enter which dice you want to roll [1,2,3] (exit with q): ");
//Calling method diceToThrow, chosing input 1,2,3 or q
diceToThrow = scan.next().charAt(0);
tärningsKast(diceToThrow);
//sum = dice1 + dice2 + dice3
calcSum();
//If user gets 12 store int wins as +1, if lose store int loss as +1
winOrLose();
//Printing dices, if input from user is 1, it shows sum of first dice etc.
System.out.printf(dice1 + " " + dice2 + " " + dice3 + " sum: " + sum + " #win: " + wins + " #loss: " + losses+ " ");
//Calling method for round score.
checkRounds();
main(args);
//Method created for sum calculating, called in Main method
}static void calcSum(){
sum = (dice1 + dice2 + dice3);
}
//Method created for dice1, dice2, dice3 and char q (as exit). Dice generates random number between 0-5 and always adds + 1 (1-6)
static void tärningsKast(char diceToThrow){
Random rand = new Random();
//If user input = 1, generate dice1
if(diceToThrow == '1' && !dice1Thrown){
dice1 = rand.nextInt(6) + 1;
dice1Thrown = true;
}
//If user input = 2, generate dice2
else if(diceToThrow == '2' && !dice2Thrown){
dice2 = rand.nextInt(6) +1;
//If user input = 3, generate dice3
}else if(diceToThrow == '3' && !dice3Thrown){
dice3 = rand.nextInt(6) + 1;
dice3Thrown = true;
//If user input = char q, Print "Game Over!" and exit game.
}else if(diceToThrow == 'q'){
System.out.println("Game Over!");
System.exit(0);
}
}
static void winOrLose(){
if(sum == 12){
wins++;
}
else if(sum > 12){
losses++;
}
}
static void checkRounds(){
rounds++;
if(rounds == 3)
{
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
rounds = 0;
}
}
}
When you are going for the next round, the method tärningsKast() is only going to work again and again once each round passes if the dice is not thrown.
Meaning that once a round finishes and you are going to start another round, you have to set that the dices are not thrown, since the round is going to start right after.
The solution I found is to set the dice1Thrown, dice2Thrown and dice3Thrown to false on the if statement that prints that the next round is starting.
static void checkRounds(){
rounds++;
if(rounds == 3)
{
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
rounds = 0;
dice1Thrown = false;
dice2Thrown = false;
dice3Thrown = false;
}
After that the game seems to be working fine.
The steps I made to find that it, were:
Set a break point to debug the line that prints "Next round".
Once the debugger reachs that line, set a break point in the first line of the method tärningsKast(), then check that in each check of the if, else if and etc. the diceNThrown variables are all still setted to true, so none of the conditions will match.
Regarding the question:
"You mean, if you wanted to stop the game in the round 2 ?"
"Yeah exactly like that"
First I'd use you checkRounds() method to check if it were to stop the game, meaning if the user already played two rounds.
Second I would move the logic that move to the next round to a method that checks attemps, intead of rounds, since we will move to the next round every time the user already had three attempts.
And finally before moving to the next round I would be increasing the number of rounds, and right after checking if the number of rounds if the expected number of rounds to stop, that way you can play the game with the limit of rounds you desire to.
//Declaring int variables for all 3 dice
static int dice1;
static int dice2;
static int dice3;
//Declaring true/false for which dice that is thrown, can't be thrown more than 1 time in each round.
static boolean dice1Thrown = false;
static boolean dice2Thrown = false;
static boolean dice3Thrown = false;
//Method for which dice is thrown - the input the user choses (1, 2, 3 or q)
static char diceToThrow;
//Method that checks what number 1-6 the dice roll. sum by default is 0
static int sum = 0;
//Method for keep track of # wins
static int wins;
//Method keep tracks of # losses
static int losses;
//If firstGame = true it will print "Welcome to the game 12" if false, it doesn't print that every round
static boolean firstGame = true;
//Int for keeping track of when dice thrown is = 3. Go to next round.
static int attempts;
// keeping track of the number of rounds
static int rounds = 0;
// desired number of rounds to play
static final int LIMIT_OF_ROUNDS = 5;
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
if(firstGame)
{
System.out.println("Welcome to the game 12. You must roll 1-3 dice and try to get the sum 12 ... ");
firstGame = false;
}
System.out.printf("Enter which dice you want to roll [1,2,3] (exit with q): ");
//Calling method diceToThrow, chosing input 1,2,3 or q
diceToThrow = scan.next().charAt(0);
tärningsKast(diceToThrow);
//sum = dice1 + dice2 + dice3
calcSum();
//If user gets 12 store int wins as +1, if lose store int loss as +1
winOrLose();
//Printing dices, if input from user is 1, it shows sum of first dice etc.
System.out.printf(dice1 + " " + dice2 + " " + dice3 + " sum: " + sum + " #win: " + wins + " #loss: " + losses+ " ");
//Calling method for round score.
checkAttempts();
main(args);
//Method created for sum calculating, called in Main method
}static void calcSum(){
sum = (dice1 + dice2 + dice3);
}
//Method created for dice1, dice2, dice3 and char q (as exit). Dice generates random number between 0-5 and always adds + 1 (1-6)
static void tärningsKast(char diceToThrow){
Random rand = new Random();
//If user input = 1, generate dice1
if(diceToThrow == '1' && !dice1Thrown){
dice1 = rand.nextInt(6) + 1;
dice1Thrown = true;
}
//If user input = 2, generate dice2
else if(diceToThrow == '2' && !dice2Thrown){
dice2 = rand.nextInt(6) +1;
//If user input = 3, generate dice3
}else if(diceToThrow == '3' && !dice3Thrown){
dice3 = rand.nextInt(6) + 1;
dice3Thrown = true;
//If user input = char q, Print "Game Over!" and exit game.
}else if(diceToThrow == 'q'){
System.out.println("Game Over!");
System.exit(0);
}
}
static void winOrLose(){
if(sum == 12){
wins++;
}
else if(sum > 12){
losses++;
}
}
static void checkAttempts(){
attempts++;
if(attempts == 3)
{
rounds++;
checkRounds(rounds);
System.out.println("\n" + "Next round!");
dice1 = 0;
dice2 = 0;
dice3 = 0;
attempts = 0;
dice1Thrown = false;
dice2Thrown = false;
dice3Thrown = false;
}
}
static void checkRounds(int rounds) {
if (rounds == LIMIT_OF_ROUNDS) {
tärningsKast('q');
}
}
I'm having a problem with an infinite loop and not 100% sure where the issue is.
I'm unsure if there is an issue within my "while" statement or there's a wrong sign or bracket.
This is my first time doing this and seems it doesn't like my post being "mostly code", so disregard this paragraph of me typing away to remove the message :)
import java.util.Random; // Needed for the Random class
import java.util.Scanner; // Needed for the Scanner class
/**
This class simulates rolling a pair of dice 10,000 times
and counts the number of times doubles of are rolled for
each different pair of doubles.
*/
public class RollDice {
public static void main(String[] args){
final int NUMBER = 10000; // Number of dice rolls
// A random number generator used in
// simulating the rolling of dice
Random generator = new Random();
int die1Value; // Value of the first die
int die2Value; // Value of the second die
int count = -1; // Total number of dice rolls
int snakeEyes = 0; // Number of snake eyes rolls
int twos = 0; // Number of double two rolls
int threes = 0; // Number of double three rolls
int fours = 0; // Number of double four rolls
int fives = 0; // Number of double five rolls
int sixes = 0; // Number of double six rolls
int runAgain = 0; // Sentinel variable
Scanner keyboard = new Scanner(System.in); //Scanner Object
while(runAgain == 0){ //This is a sentinel loop
// TASK #1 Enter your code for the algorithm here
while(count < NUMBER)
{
// Roll both dice
die1Value = generator.nextInt(6) + 1;
die2Value = generator.nextInt(6) + 1;
// Check to see if both dice are equal
if(die1Value == die2Value)
{
// Check dice values and update counts
if(die1Value == 1)
snakeEyes++;
else if(die1Value == 2)
twos++;
else if(die1Value == 3)
threes++;
else if(die1Value == 4)
fours++;
else if(die1Value == 5)
fives++;
else
sixes++;
}
count++;
}
// Display the results
System.out.println ("You rolled snake eyes " +
snakeEyes + " out of " +
count + " rolls.");
System.out.println ("You rolled double twos " +
twos + " out of " + count +
" rolls.");
System.out.println ("You rolled double threes " +
threes + " out of " + count +
" rolls.");
System.out.println ("You rolled double fours " +
fours + " out of " + count +
" rolls.");
System.out.println ("You rolled double fives " +
fives + " out of " + count +
" rolls.");
System.out.println ("You rolled double sixes " +
sixes + " out of " + count +
" rolls.");
}
// Reset all counts [Every time you want to run again]
snakeEyes = 0;
twos = 0;
threes = 0;
fours = 0;
fives = 0;
sixes = 0;
count = 0;
// Ask the user if they wish to run again, 0 = yes, -1 = no
System.out.println("Do you wish to run again?");
System.out.println("Enter a 0 for yes or a -1 for no");
// Read user's response
runAgain = keyboard.nextInt();
}
}
I formatted your code and in addition to what Brakke Baviaan Says, this part of your code should be inside the while loop:
// Reset all counts [Every time you want to run again]
snakeEyes = 0;
twos = 0;
threes = 0;
fours = 0;
fives = 0;
sixes = 0;
count = 0;
// Ask the user if they wish to run again, 0 = yes, -1 = no
System.out.println("Do you wish to run again?");
System.out.println("Enter a 0 for yes or a -1 for no");
// Read user's response
runAgain = keyboard.nextInt();
Currently is outside so thats why it keeps looping as you never get to update the variable runAgain
You are using a sentinel variable. A sentinel variable is a variable that controls the termination of a loop. In your case, as the comment points out, the sentinel variable runAgain never gets updated, thus the loop will continue infinately.
Boolean sentinel = true;
while(sentinel){
doSomething();
if(someCondition == true){
sentinel = false; //loop will end after function reaching this point
};
The count reset should be inside the first while.
I'm little bit confused how to calculate percentage based on input values (eg: pick for team)
Scanner input = new Scanner(System.in);
System.out.println("1 for Team one, 2 for Team two, 3 for draw, 9 for quit");
int pick = 0;
int team1 = 0;
int team2 = 0;
int draw = 0;
while (pick != 9) {
pick = input.nextInt();
if (pick == 1) {
team1 += 1;
} else if (pick == 2) {
team2 += 1;
} else if (pick == 3) {
draw += 1;
}
}
System.out.println(team1);
System.out.println(team2);
System.out.println(draw);
int total = team1 + team2 + draw;
System.out.println(total);
This will print individually and total.
l want to print for example if all values are picked 2 times from input:
"Team 1 = 33.3%, Team 2 = 33.3%, draw = 33.3%" and so one for different type of picks. Thanks
You are almost there. Now, all you just need is a counter to count the iterations and finally divide the score of team1, team2 and draw by the value of the counter after multiplying them with 100.0 to get the percentage score.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("1 for Team one, 2 for Team two, 3 for draw, 9 for quit");
int pick = 0;
int team1 = 0;
int team2 = 0;
int draw = 0;
int count = -1;
while (pick != 9) {
pick = input.nextInt();
if (pick == 1) {
team1 += 1;
} else if (pick == 2) {
team2 += 1;
} else if (pick == 3) {
draw += 1;
}
count++;
}
System.out.printf("Percentage score of team1: %.1f%n", (team1 * 100.0 / count));
System.out.printf("Percentage score of team2: %.1f%n", (team2 * 100.0 / count));
System.out.printf("Percentage score of draw: %.1f%n", (draw * 100.0 / count));
}
}
A sample run:
1 for Team one, 2 for Team two, 3 for draw, 9 for quit
1
2
3
3
2
1
9
Percentage score of team1: 33.3
Percentage score of team2: 33.3
Percentage score of draw: 33.3
To get the percentage of each price you have to do:
int persentageteam1 = team1*100/(team1+team2+team3);
and the same for the others...
Explanation:
What you do here is divide the price of which you want to find the persentage with the sum of the rest of the other and do this x100
A percentage of a number is calculated basing on the following principle (or at least as it is taught is my school) :
Say, you need to figure out a number percent ratio of another one, let it be firstNumber and secondNumber. Then, firstNumber=100% and secondNumber=x. From that we get the proportion: firstNumber/secondNumber = 100%/x, consequently, x=(secondNumber*100)/firstNumber. That is, in your case, the firstNumber is the pick summary of all teams and the secondNumber - the team which percentage you want to determine. For example
//your code
int pickSummary=team1+team2+team3+draw;
int team1Percentage=team1*100/pickSummary;
System.out.println(team1Percentage);
//and so on
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 + "%");
}
}
I'm trying to write a JAVA code which keeps accepting integers until it reaches a specific number, so after that, the user has to input 0s for the remaining inputs in order to keep the sum of inputs <= condition
EXAMPLE: if i have 5 cups of coffees and 5 shots available, the user enters 3 shots for the first cup of coffee, and then 2 shots for the second cup. So now 3+2 = 5 shots which is the number of coffee shots available, so for the next 3 coffee cups the user SHOULD enter 0s to proceed, otherwise it keeps looping.
This is how my code looks like:
int add = 0;
int[] numberOfCoffeeShots = new int[coffeeCupsAvailable]; //input number of shots for every coffee cup
int i; //declares i
for (i = 0; i < coffeCupsWanted; i++) { //iterate over a range of values.
System.out.print("How many coffee shots in cup " + (i + 1) + "? ");
numberOfCoffeeShots[i] = keyboard.nextInt();
add += (numberOfCoffeeShots[i]); //adding the number of shots in each cup
while (numberOfCoffeeShots[i] < 0) {
System.out.println("Does not compute. Try again.");
System.out.print("How many coffee shots in cup " + (i + 1) + "? ");
numberOfCoffeeShots[i] = keyboard.nextInt();
}
while (numberOfCoffeeShots[i] > coffeeShotsAvailable) {
System.out.println("There are only " + coffeeShotsAvailable + " coffee shots left. Try again.");
System.out.print("How many coffee shots in cup " + (i + 1) + "? ");
numberOfCoffeeShots[i] = keyboard.nextInt();
}
I still need the while loop for the sum of inputs > coffeeShotsAvailable
Any help please about this idea ?? Thanks
Here's my solution. Beneath this code is a complete walkthrough the program and why it works.
public class CoffeeAndShots{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int numberOfCoffees = 5;
int numberOfShots = 5;
int[] coffeeShots = new int[numberOfCoffees];
for(int i = 0; i < numberOfCoffees; i++)
coffeeShots[i] = -1;
for(int i = 0; i < numberOfCoffees; i++){
int input;
while(coffeeShots[i] < 0){
System.out.println("How many shots for coffee cup " + (i + 1) + "?");
input = keyboard.nextInt();
if(input > numberOfShots)
System.out.println("You don't have that many shots");
else{
coffeeShots[i] = input;
numberOfShots = numberOfShots - input;
}
}
}
for(int i = 0; i < numberOfCoffees; i++)
System.out.println(coffeeShots[i] + " shots for coffee cup " + (i + 1));
}
}
coffeeShots is an integer array initialized with a number of terms equal to the number of coffee cups we're working with. In the for loop immediately after, each term in that array is set to -1. This is because later in the program there is a possibility that the user does not allocate any shots for the specific coffee cup. In the next for loop, we go through each term in the array of coffee cups. For each cup, we will ask the user how many shots they want for that cup until a value greater than or equal to 0 is accepted. In accepting values, we need to make sure that the number of shots specified is actually available. If it is, we set the number of shots for that cup to the inputted value, then deduct our total shots by the number we allocated. When it's all said and done, we print the entire array.