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.
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');
}
}
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 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;
}
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!
I'm new to Java and also new to while, for, and if/else statements. I've really been struggling with this beast of a problem.
The code and description is below. It compiles, but I'm it doesn't calculate as expected. I'm not really sure if it's a mathematical logic error, loop layout error, or both.
I've been grinding my gears for quite some time now, and I'm not able to see it. I feel like I'm really close... but still so far away.
Code:
/*
This program uses a while loop to to request two numbers and output (inclusively) the odd numbers between them,
the sum of the even numbers between them, the numbers and their squares between 1 & 10, the sum of the squares
of odd numbers.
*/
import java.io.*;
import java.util.*;
public class SumOfaSquare
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int firstnum = 0, secondnum = 0, tempnum = 0;
int sum = 0,squaresum = 0, squarenum = 0;
int number = 1;
String oddOutputMessage = "The odd numbers between" + firstnum + " and " + secondnum + " inclusively are:";
String evenSumMessage = "The sum of all even numbers between " + firstnum + " and " + secondnum + "is: ";
String oddSquareMessage = "The odd numbers and their squares are : ";
String squareMessage = "The numbers and their squares from 1-10 are : ";
System.out.println ("Please enter 2 integers. The first number should be greater than the second: ");
firstnum = console.nextInt();
secondnum = console.nextInt();
//used to find out if first number is greater than the second. If not, inform user of error.
if (firstnum > secondnum)
{
tempnum = firstnum;
System.out.println ("You entered: " + firstnum + " and: " + secondnum);
}
else
System.out.println ("Your first number was not greater than your second number. Please try again.");
//while the frist number is greater, do this....
while (tempnum <= secondnum)
{
//if it's odd....
if (tempnum %2 == 1)
{
oddOutputMessage = (oddOutputMessage + tempnum + " ");
squaresum = (squaresum + tempnum * tempnum);
}
//otherwise it's even..
else
{
sum = sum + tempnum;
evenSumMessage = (evenSumMessage + sum + " ");
tempnum++;
}
}
// figures squares from 1 - 10
while (number <=10)
{
squarenum = (squarenum + number * number);
squareMessage = (squareMessage + number + " " + squarenum);
number++;
}
oddSquareMessage = oddSquareMessage + squaresum;
System.out.println (oddOutputMessage);
System.out.println (oddOutputMessage);
System.out.println (squareMessage);
System.out.println (evenSumMessage);
System.out.println (oddSquareMessage);
}
}
In your first loop, think hard about the conditions under which you increment tempnum. What happens when it's odd? Does tempnum get incremented?
There are a number of problems with your code. I'd rather you work through the problem yourself. You can use "println" debugging to print out the variables along the way if you don't know how to debug code.
Take the input 3 and 1 and walk through your program line by line and think about what the answer is going to be in your head (or on paper). See if that matches your expected results.
Here are some general comments about your code:
Consider breaking the different output into different subroutines: dumpOddNumbers(low, high), sumEvenNumbers(low, high), ...
Try to limit a variables scope as much as possible. Don't define the variables at the top and then use them later. Try to define them right before you need them. This will limit your unintended consequences. Try to not re-use variables unless it is temporary counters.
while (tempnum <= secondnum) These sort of lines should be for loops. One of the problems with the code is that if the first number is < then the second (the input 1 10 for example), the program loops forever because tempnum is not incremented if the number is odd.
while (tempnum <= secondnum) should probably be for (int tempnum = firstnum; tempnum <= secondnum; tempnum++)
while (number <= 10) should be for (int number = 1; number <= 10; number++)
You define the message at the top of your program but you shouldn't tack on results later. Do something like println(msgString + resultValue).
Take a look at StringBuilder() instead of msg = msg + ... type of logic. Much more efficient.
When you check the numbers are in the right order and spit out an error message, are you sure you want to continue? I think you should return there.
The following code does not match the comment. Which is correct?
// while the frist number is greater, do this
while (tempnum <= secondnum) {
Hope this helps.