JAVA help of getting sum of inputs - java

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.

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

Guessing game with minimum guesses used not working in Java

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

Java averaging calculator with defined number of entries

I've seen several average calculators but none with this specific function.
Basically, I want it to ask "How many numbers would you like to average?" then "Enter your number" and continue to prompt "Enter your number" after each entry until the "How many numbers..." quantity is fulfilled. I know it's a count-loop (sorry if my jargon is off...I'm only in my second semester of computer programming) but I don't know how to set it up. Thanks in advance for your answers. Here's what I have so far:
import java.util.Scanner;
public class TestScoreApp
{
public static void main(String[] args)
{
// welcome the user to the program
System.out.println("Welcome to the Test Average Calculator!");
System.out.println(); // print a blank line
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
// initialize variables and create a Scanner object
int scoreTotal;
int scoreCount;
int testScore;
Scanner sc = new Scanner(System.in);
// perform calculations until choice isn't equal to "y" or "Y"
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
// get the number of grades to be averaged from the user
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
// get the input from the user
System.out.print("Enter score: ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100)
System.out.println("Invalid entry, not counted");
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
System.out.print("Would you like to average more grades? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
Your approach is near about right except some mistakes. You want to take input until 'n' is pressed and then the average would be shown. That means the average calculation must be done outside the loop, when taking input ends.
If you want to take input with a predefined number from input instead of 'y'/'n' approach, you can reuse your while loop:
int numOfInput = sc.nextInt(); // how many number will be entered
while(numOfInput > 0) {
// take every input and add to total
--numOfInput;
}
// average calculation
Also, a little logical mistake in input validation check.
if (testScore <= 100) // for less or equal 100
{
scoreTotal = scoreTotal + testScore;
}
else if (testScore >= 100) // for greater or equal 100
System.out.println("Invalid entry, not counted");
Both condition checks whether the number is equal to 100, which is not expected. If you allow only number less than 100, then you could write:
if (testScore < 100) {
scoreTotal += testScore;
}
else {
System.out.println("Invalid entry, not counted");
}
So you want to average scoreCount items, or keep averaging until the user has input "n" ?
If it's the first case (As you've described in your question) and you want to average for scoreCount times, you need to change the condition on your while loop.
System.out.print("How many scores would you like to average? ");
scoreCount = sc.nextInt();
scoreTotal = 0;
for(int i=0; i<scoreCount; i++){
scoreTotal += sc.nextInt();
System.out.print("Okay please enter next...");
}
System.out.print("Average is " + scoreTotal/scoreCount);
If you want to do it with a while, just keep an index, int index=0;, increment the index on each iteration and check if you've exceeded the index.
while (index < scoreCount)
scoreTotal += sc.nextInt();
index++;
System.out.print("Average is " + scoreTotal/scoreCount);
That is what you need:
for( int i = 0; i < scoreCount; i++){
System.out.print("Enter score: ");
testScore = sc.nextInt();
}
The for loop creates integer i to hold its looping index
int i;
And each loop asks is i bigger than scoreCount and if not loop again.
i < scoreCount;
And after each loop it adds one to i.
i++

Individually sum random numbers not in an array?

This is part of a school assignment which I've already turned in, I was graded down in one portion because the total sum of the random numbers was supposed to be adding the individual numbers together, not each line.
So if the lines read:
1 2 3
4 5 6
The total should be 21, not 579 as my program is doing now. I've really been struggling trying to figure this out. I tried generating a different random number object for each integer, for a total of three of them but that completely screwed up my output.
We're learning arrays next week, and after researching online I could do this easily with an array, but the assignment was to be done without arrays. How can I sum each entry individually? Thanks for any help!
Here is my code:
import java.util.Random;
import java.util.Scanner;
public class lottery {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int gameType, gameTimes;
int randomNums, lotNum, sum = 0;
System.out.println("\t\t Welcome to\n \t\tJAVA LOTTERY!\n\n\n");
System.out.print(" Would you like to play with 3, 4, or 5 numbers? ");
gameType = input.nextInt();
System.out.println("\n\n Now think about a number with " + gameType + " digits and remember it!\n\n\n");
System.out.print(" How many games should we play? ");
gameTimes = input.nextInt();
System.out.println("\n\n We're all done! We played " + gameTimes + " games!\n\n" +
" The numbers randomly selected were: ");
for(int i = 0; i < gameTimes; i++)
{
lotNum = 0;
for(int j = 0; j < gameType; j++)
{
randomNums = (new Random()).nextInt(10);
lotNum = (lotNum * 10) + randomNums;
System.out.print(" " + randomNums);
}//end nested for loop
System.out.println();
sum += lotNum;
}//end for loop
System.out.println("\n\nThe total of all of the numbers was " + sum );
input.close();
}//end main method
}//end lottery class
Change
lotNum = (lotNum * 10) + randomNums;
to
lotNum += randomNums;

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!

Categories

Resources