java dicegolfgame - whileloop - java

I'm stuck on this while loop question, would be glad if someone could spot out where I am going wrong :)
Golf game Write a program that uses a while loop to play a dice golf game. The distance to the hole starts at 100m. The person repeatedly chooses which club to use. The different choices each correspond to a different sided virtual ‘dice’ to roll – ie giving a random number. If they choose club 1 (a putter) they roll a number from 0-5 representing the distance hit. If they choose club 2 (for pitching) they roll a number from 0-30. If they choose club 3 (an iron) they roll a number from 0 to 150. After each roll that number is subtracted from the distance to the hole (with negative distances being made positive for the next round). They keep rolling until they get the distance to exactly 0. When they do the number of shots taken is printed.
The following shows an example run of the program:
Distance to hole 100m. Which club (1-putting, 2-pitching or 3-iron) 3
You hit it...120m
Distance to hole 20m. Which club (1-putting, 2-pitching or 3-iron) 2
You hit it...16m
Distance to hole 4m. Which club (1-putting, 2-pitching or 3-iron) 1
You hit it...1m
Distance to hole 3m. Which club (1-putting, 2-pitching or 3-iron) 1
You hit it...3m
Congratulations. You took 4 shots.
I am new to java, below is what I managed to get done, but shows error on: while (input.equals !( "1" || "2" || "3") ). I'm not sure whether its done correctly and spent ages on this, would be glad if someone could help out on the question problem :) Much appreciated.
public static void dicegolfgame(String[] args)
{
String input = "";
int difference = 0;
int newdistance = 0;
int distance = 0;
int i = 0;
while (input.equals ( "1" || "2" || "3") )
{
Random roll2 = new Random();
distance = roll2.nextInt(100);
input = JOptionPane.showInputDialog ( "distance to hole " + distance + " Which club (1-putting), 2-(pitching) or 3-iron");
while (difference > 0 && difference < 0)
if (input.equals ("1"))
{
Random roll = new Random();
newdistance = roll.nextInt(5);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
else if (input.equals ("2"))
{
Random roll = new Random();
newdistance = roll.nextInt(30);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
else if (input.equals ("3"))
{
Random roll = new Random();
newdistance = roll.nextInt(150);
i = i+1;
JOptionPane.showMessageDialog(null, "you hit ..." + newdistance + "m");
difference = distance - newdistance;
}
if (difference == 0)
{
break;
JOptionPane.showMessageDialog(null, "Congratulations, you took" + i + "shots.");
}

It's the distance to the hole that determines whether the golfer has to shoot again or not - so that should be in the while loop. I've added some comments in the code:
String input = "";
int distance = 100;
int numberOfHits = 0;
int hit = 0;
while (distance > 0) {
numberOfHits++;//increasing the nuber of hits
input = JOptionPane.showInputDialog("distance to hole " + distance + " Which club (1-putting), 2-(pitching) or 3-iron");
switch (input) {//if you don't know switch you coukd use if-else
case "1":
Random roll = new Random();
hit = roll.nextInt(6);//a random int netween 0-5
JOptionPane.showMessageDialog(null, "you hit ..." + hit + "m");
distance -= hit;//sets the new distance to the old distance subtracted the hit
distance = Math.abs(distance);//if distance is negative make it positive
break;
case "2":
roll = new Random();
hit = roll.nextInt(31);
JOptionPane.showMessageDialog(null, "you hit ..." + hit + "m");
distance -= hit;
distance = Math.abs(distance);
break;
case "3":
roll = new Random();
hit = roll.nextInt(151);
JOptionPane.showMessageDialog(null, "you hit ..." + hit + "m");
distance -= hit;
distance = Math.abs(distance);
break;
}
}
//when we are out of the loop the distance is zero
JOptionPane.showMessageDialog(null, "Congratulations, you took " + numberOfHits + " shots.");

Related

Creating a lottery draw method

Hello.
I'm working on a lottery system in a game that I'm working on.
My goal is to get a player randomly based on their amount input and the total value of the lottery pot at the moment of the drawing. E.G Pot is 100k, Player1 has put in 10k, and Player2 has put in 20k, meaning Player 1 has 1/10 chance of winning and Player2 has a 2/10 chance of winning.
totalPot, this is the total value of the pot
randomNR, this is a random number generation
userInput, this is the total input that the user has put into the lottery.
player, this is the player who inputted the amount above
I have already tried this:
public static void drawLottery() {
int totalPot = lotteryPot - 250;
int randomNR = Misc.randomInt(0, lotteryPot);
List<Player> keys = new ArrayList<Player>(lotteryEntries.keySet());
Collections.shuffle(keys);
for(int i = 0; i < totalPot;) {
for (Player o : keys) {
i += lotteryEntries.get(o);
if (i >= randomNR) {
System.out.println("Winner: " + o.getUsername() + " -> Random number: " + randomNR);
}
break;
}
break;
}
}
But that just caused the same player to be drawn over and over again.
I don't know what to do and help would be greatly appreciated.
You can iterate over all the lottery entries and keep a cumulative total. The first time the cumulative total exceeds the winning number is the player that has won.
For example:
Player 1: 20
Player 2: 30
Player 3: 50
Player 4: 10
The winning number is chosen to be 51. The cumulative total starts at 20. This is not greater than 51, so player 1 has not won. Then we increment to 50. Not greater than 51, player 2 has not won. Then we increment to 100 which greater than 51 so player 3 has won.
public static Player getWinner(int winningNumber, Map<Player, Integer> lotteryEntries)
{
int cumulativeProbability = 0;
for (Map.Entry<Player, Integer> entry : lotteryEntries.entrySet())
{
cumulativeProbability += entry.getValue();
if (cumulativeProbability >= winningNumber)
{
return entry.getKey();
}
}
throw new RuntimeException("Winning number not within total pot size");
}
Use the pot to ponderate your random choice. Pick a number inside the pot. define a range in the pot for every player. If the picked number is in the range, this player is the winner.
For example, the pot is 30. Player 1 put 10 and player 2 put 20. You pick a random number between 0 and 30. Let's say random gives us 23. The range corresponding to player 1 is 0 to 10 and the range corresponding to player 2 is 10 to 30. Then player 2 has won.
This should look like this :
//pick a random number inside the pot
Random rand = new Random();
int randNum = rand.nextInt(totalPot);
//Define the pot range corresponding to a player
int rangeStart = 0;
int rangeEnd = 0;
//go through all enties (all players)
for(Entry entry : lotteryEntries.entries()) {
//Define the range corresponding to this player
value = entry.getValue()
rangeStart = rangeEnd;
rangeEnd += value;
//If the picked random num is in the range, this player is the winner
if( randNum >= rangeStart && randNum < rangeEnd) {
System.out.println("Winner: " + entry.getKey().getUsername()):
System.out.println("randNum: " + randNum);
break;
}
}

Simple Java Program Isn't Getting Intended Output

import java.util.Random;
public class Player {
int att;
int str;
int def;
int hp;
int attackRoll;
int defenceRoll;
int maxHit;
//A player has variable attack, strength, defence, and hp stats
//attack = determines accuracy, strength = determines damage, defence = determines ability to block hits
public Player(int attack, int strength, int defence, int hitpoints)
{
attack = att;
strength = str;
defence = def;
hitpoints = hp;
/*
attackRoll and defenceRoll are used by the 2 players to determine probability
of successfully scoring a hit, in m sample testing attRoll will always be
higher than defRoll; they are integer numbers used in below method
*/
attackRoll = (this.att + 3)*(90+64);
defenceRoll = (this.def + 3)*(0+64);
maxHit = (int) ((0.5) + ((this.str + 0 + 8.0)*(86.0+64.0))/(640.0));
//maxHit determines the maximum number player can deal each attack
}
//this determines if p1 successfully lands a hit on p2, true if so, false if not
//accuracy is calculated as a probability, ie .7 probability of hitting
//in which case there is .7 probability of being true and .3 of being false
public static boolean hit(Player p1, Player p2)
{
double accuracy;
if (p1.attackRoll > p2.defenceRoll)
{
accuracy = 1.0 - ((double)(p2.defenceRoll+2.0)/(2*(p1.attackRoll+1.0)));
}
else
{
accuracy = (double) (p1.attackRoll/(2*(p2.defenceRoll+1.0)));
}
Random r = new Random();
System.out.println("Accuracy: " + accuracy);
return r.nextDouble() <= accuracy;
//idea is that if accuracy is .7 for example, nextDouble() generates
//between 0-1.0 so the probability that nextDouble() is <= .7 is .7, what we want
}
//calculates damage p1 does to p2, if hit returns true
public static void attack(Player attacker, Player defender)
{
int damage = 0;
if(!hit(attacker, defender)) return; //if the attacker missed, damage is 0, defender doesn't lose hp
//if p1 successfully landed a hit on p2 as determined in previous method
else if(hit(attacker, defender))
{
Random r = new Random();
damage = r.nextInt(attacker.maxHit+1); //p1 deals (0 to maxHit) damage on p2 from that attack
defender.hp -= damage; //p2 loses that much hp
}
}
public static void main(String[] args) {
int p1wins = 0; //counts number of times p1 won
int p2wins = 0; //counts number of times p2 won
int firstCounter = 0; //counts the number of times p1 went first, should be near 50% as its randomly decided
int secondCounter = 0; //couonts the number of times p2 went first, should be near 50%
for (int i = 1; i <= 10000; i++) //10000 trials of p1 and p2 battling
{
Player p1 = new Player(99, 99, 99, 99); //set p1's attack, strength, defence, hp to 99
Player p2 = new Player(99, 99, 99, 40); //p2 only has 40 hp, therefore p2 should lose most of the time
Random r = new Random();
int first = r.nextInt(2); //determines which player attacks first
if(first == 0) firstCounter++;
if(first == 1) secondCounter++;
while((p1.hp>0) && (p2.hp>0)) //the fight goes on until one player dies (hp is <= 0)
{
if(first == 0) //if player 1 attacks first
{
attack(p1, p2); //player 1 attacks player 2
if(p2.hp <= 0) break; //if player 2's hp goes 0 or below from that attack, he dies and there's no more fighting
attack(p2, p1); //then p2 attacks p1, and repeat
if(p1.hp <= 0) break;
}
else if (first == 1) //if player 2 attacks first
{
attack(p2, p1); //player 2 attacks player 1
if(p1.hp <= 0) break;
attack(p1, p2);
if(p2.hp <= 0) break;
}
}
if(p1.hp <= 0) p2wins++;
else if(p2.hp <= 0) p1wins++;
}
System.out.println("p1 won " + p1wins + " times."); //prints number of times p1 wins
System.out.println("p2 won " + p2wins + " times.");
System.out.println(firstCounter); //prints number of times p1 went first, should be near 50% with large sample size
System.out.println(secondCounter);
}
}
The above code is a program that simulates 2 players fighting.
The main idea is to understand that a player has 4 stats (attack, strength, defense, hp) and that if two players fight with the same stats (ie 99,99,99,99 both), then the probability that anyone will win is naturally about 50%.
The problem I'm encountering is that the program makes p2 win every single game, even with stats that are obviously vastly inferior
(ie p1 having 99 att, 99 str, 99 def, 99 hp p2 having 99 att, 99 str, 99 def, but 20 hp), thus p2 would die much sooner in most trials, but a run of 10000 fights displays p2 winning all 10000 of them, which is obviously wrong and not intended. I can't figure out why p2 is winning 100% of the time.
You have an error at the beginning of the Player constructor.
Assignments' order are wrong. The correct way is:
att = attack;
str = strength;
def = defence;
hp = hitpoints;
Otherwise, p1.hp and p2.hp are always 0.

Dice game with two players, 3 die choices and cards

I am trying to write code for a game that has a player and a computer roll dice until one, or both, reach 250( its possible for them to tie). The player and the computer can choose from 1 of 3 die choices. One - 24 sided tie, two - 10 sided die, or three - 6 sided die. There is a bonus for the 10 and 6 sided die if the die are all the same. There are 2 "lakes" where if the player lands in them the player has to go back to the lower number right before the beginning of the lake, there is also a muddy swamp where every move the player makes while in the swamp is cut in half. For every 10 spots (10, 20, 30, 40 ETC.) the player randomly draws a card. There are 11 different cards the player can randomly get:
1-4: player moves ahead a random amount from 1-6
5: player moves ahead a random amount from 4-11 (random 8 + 4)
6: player moves to where the other player is (see below)
7: player moves back to the beginning (moves to location 0)
8-9: player moves back a random amount from 1-6
10-11: player moves back a random amount from 4-11
I have a few problems. My first problem is that the die rolls do not change after every turn, they will remain the same. So if I choose 3 die I might get 3 random numbers, if I choose those die again I will get those same 3 numbers.
I also cannot seem to get the players die count to correctly update. If the player rolls 18 total points and the next turn he rolls 14 the count will go from 18 to 14.
My third problem is it seems like no matter what I do the print statement for the lakes,muddy patch and the winner announcement always print. I have tried a few different things and nothing seems to work.
I am new at code writing ( this is my 4th program written) and do not have extensive knowledge to know what is wrong. The code does not have to be expertly done, I just would like it to work properly. Any and all help is greatly appreciated.
/*This program will create a "Board" game. Each player can choose
from several different types of die. The computer and user will take
turns "rolling" a dice. There are several obstacles that can send one
of the players back. The goal is to get above 250*/
import java.util.*;
public class Project4 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//assigning variables
int p1, p2;
p1=p2=0;
int spacesmoved = 0;
//Setting up the randomization of the 24 sided die
int minimum1 = 1;
int maximum1 = 24;
Random rn1 = new Random();
int range1 = maximum1 - minimum1 + 1;
int die1 = rn1.nextInt(range1) + minimum1;
//Setting up the randomization of the 10 sided die
int minimum2 = 1;
int maximum2 = 10;
Random rn2 = new Random();
int range2 = maximum2 - minimum2+ 1;
int die2 = rn2.nextInt(range2) + minimum2;
int die22 = rn2.nextInt(range2) + minimum2;
int die222 = rn2.nextInt(range2) + minimum2;
//Setting up the randomization of the 6 sided die
int minimum3 = 1;
int maximum3 = 10;
Random rn3 = new Random();
int range3 = maximum3 - minimum3+ 1;
int die3 = rn3.nextInt(range3) + minimum3;
int die33 = rn3.nextInt(range3) + minimum3;
int die333 = rn3.nextInt(range3) + minimum3;
//Setting a loop for the players to take turns until one, or both, reach > 250
while (p1 <= 250 && p2 <= 250) {
{System.out.println(" Current positions. Player: " + p1 + " Computer: " + p2);
System.out.println("Which die would you like to roll? die1(1) = one 24-sided die, die2(2) = two 10-sided dice, die3(3) = three 6-sided dice: ");
String diechoice = in.nextLine().toLowerCase();
//Getting the die roll if the player chooses the 24 sided die
if (diechoice.equals ("1")) {
spacesmoved = (die1);
System.out.println("Player rolled a " + die1);
System.out.println("Player moves forward " + die1 +" spaces");
p1+=spacesmoved;
}
//Getting the die roll if the player chooses the two 10 sided die
if (diechoice.equals ("2")) { spacesmoved = (die2 + die22);
System.out.println("First die is " + die2);//TESTTTT
System.out.println("Second die is a " + die22);//TEST
System.out.println(die2 + die22);//TESTTTTtttt
if (die2 == die22); {
spacesmoved = (die2 + die22 + die222);
System.out.println("Player rolled doubles, player gets to roll a 3rd 10 sided die");
System.out.println("Players 3rd dice roll is " + die222);
System.out.println("Player moves forward a total of " + spacesmoved + " spots");
p1 += spacesmoved;
}
// player1spot = (currentspot + spacesmoved);
}
//Getting the die roll if the player chooses three 6 sided die
if (diechoice.equals("3")) { spacesmoved = (die3 + die33 + die333);
System.out.println("die 1 is " + die3);
System.out.println("die 2 is " + die33);
System.out.println("die 3 is " + die333);
System.out.println("Player 1 moves forward a total of " + spacesmoved + " spots");
{ if (die3 == die33)
if (die33 == die333)
spacesmoved = ( spacesmoved * 2);
p1 += spacesmoved;
}}
/*Setting up the lakes and muddy patch. If the player lands in a lake he goes back
to the lower edge of the lake. If in the mud his moves are cut in half ONLY while in the mud */
{if (spacesmoved >= (83) || spacesmoved <= (89)); spacesmoved = (82);
System.out.println("Player landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (152) || spacesmoved <= (155)); spacesmoved = (151);
System.out.println("Player landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (201) || spacesmoved <= (233)); spacesmoved = (spacesmoved / 2);
System.out.println("Player landed in mud, players turns are cut in half until player gets out");
}
//Setting up the random cards if the player lands on a 10
if (p1 % 10==0);
{ int minimum4 = 0;
int maximum4 = 11;
Random rn4 = new Random();
int range4 = maximum4 - minimum4 + 1;
int card = rn4.nextInt(range4) + minimum4;
//if player gets a card that moves them ahead a random number between 1-6
if (card >=4);
int minimum = 0;
int maximum = 6;
Random rn = new Random();
int range = maximum - minimum + 1;
int cardmove = rn.nextInt(range) + minimum;
p1 = cardmove;
//if player gets a card that moves them ahead a random number between 4-11
if (card == 5);
int minimum5 = 4;
int maximum5 = 11;
Random rn5 = new Random();
int range5 = maximum5 - minimum5 + 1;
int cardmove5 = rn5.nextInt(range5) + minimum5;
p1 = cardmove5;
//if player gets a card that moves them to the spot of the other player
if (card == 6);
p2 = p1;
//if player gets a card that moves them back to 0 (moves location to 0)
if (card ==7);
p1 = 0;
//if player gets a card that moves them back between 1-6 spaces
if (card == (8) || card == 9);
int minimum6 = 1;
int maximum6 = 6;
Random rn6 = new Random();
int range6 = maximum6 - minimum6 + 1;
int cardmove6 = rn6.nextInt(range6) + minimum6;
//if player gets a card that moves them back between 4-11 spaces
if (card == (10) || card == 11);
int minimum7 = 4;
int maximum7 = 11;
Random rn7 = new Random();
int range7 = maximum7 - minimum7 + 1;
int cardmove7 = rn7.nextInt(range7) + minimum7;
}
//Setting up the computers turn
System.out.println("Computers turn");
{
int minimum = 0;
int maximum = 2;
Random rn = new Random();
int range = maximum - minimum + 1;
int computersturn = rn.nextInt(range) + minimum;
//If computer randomly chooses a 24 sided die
spacesmoved = (die1);
System.out.println("Computer rolled a " + die1);
System.out.println("Computer moved " + die1 +" spaces");
p2+=spacesmoved;
}
//If the computer randomly chooses the two 10 sided die
if (diechoice.equals ("die2")) { spacesmoved = (die2 + die22);
System.out.println("First die is " + die2);//TESTTTT
System.out.println("Second die is a " + die22);//TEST
System.out.println(die2 + die22);//TESTTTTtttt
if (die2 == die22); {
spacesmoved = (die2 + die22 + die222);
System.out.println("Computer rolled doubles, player gets to roll a 3rd 10 sided die");
System.out.println("Computer 3rd dice roll is " + die222);
System.out.println("Computer moves a total of " + spacesmoved + " spots");
p2 += spacesmoved;
}
}
//If the computer randomly chooses three 6 sided die
if (diechoice.equals("die3")) { spacesmoved = (die3 + die33 + die333);
System.out.println("die 1 is " + die3);
System.out.println("die 2 is " + die33);
System.out.println("die 3 is " + die333);
System.out.println("Computer 1 moves a total of " + spacesmoved + " spots");
{ if (die3 == die33)
if (die33 == die333)
spacesmoved = ( spacesmoved * 2);
p2 += spacesmoved;
}
//Setting the lakes and mud for the computer
if (spacesmoved >= (83) || spacesmoved <= (89)); spacesmoved = (82);
System.out.println("Computer landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (152) || spacesmoved <= (155)); spacesmoved = (151);
System.out.println("Computer landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (201) || spacesmoved <= (233)); spacesmoved = (spacesmoved / 2);
System.out.println("Computer landed in mud, players turns are cut in half until player gets out");
//Setting up the cards for the computer
if (p1 % 10==0);
{ int minimum4 = 0;
int maximum4 = 11;
Random rn4 = new Random();
int range4 = maximum4 - minimum4 + 1;
int card = rn4.nextInt(range4) + minimum4;
//if computer gets a card that moves them ahead a random number between 1-6
if (card >=4);
int minimum = 0;
int maximum = 6;
Random rn = new Random();
int range = maximum - minimum + 1;
int cardmove = rn.nextInt(range) + minimum;
//if computer gets a card that moves them ahead a random number between 4-11
if (card == 5);
int minimum5 = 4;
int maximum5 = 11;
Random rn5 = new Random();
int range5 = maximum5 - minimum5 + 1;
int cardmove5 = rn5.nextInt(range5) + minimum5;
//if computer gets a card that moves them to the spot of the other player
if (card == 6);
p1 = p2;
//if computer gets a card that moves them back to 0 (moves location to 0)
if (card ==7);
p1 = 0;
//if computer gets a card that moves them back between 1-6 spaces
if (card == (8) || card == 9);
int minimum6 = 1;
int maximum6 = 6;
Random rn6 = new Random();
int range6 = maximum6 - minimum6 + 1;
int cardmove6 = rn6.nextInt(range6) + minimum6;
//if computer gets a card that moves them back between 4-11 spaces
if (card == (10) || card == 11);
int minimum7 = 4;
int maximum7 = 11;
Random rn7 = new Random();
int range7 = maximum7 - minimum7 + 1;
int cardmove7 = rn7.nextInt(range7) + minimum7;
}
}
//Writing a final statment showing the winner, or if both tied.
{ if (p1 > p2);
System.out.println("Player 1 wins! Good job!");
if (p2 >p1);
System.out.println("Computer wins! Better luck next time!");
if (p2 == p1);
System.out.println("The game ends in a tie!");
}
}
}
}
}
Here are the things I noticed in relation to the three problems you mentioned:
Problem number 1:
You are setting the values of the dice at the very beginning of code execution. From that point on, you aren't changing them at all. That is the cause of the problem of always rolling the same numbers every turn. You might be thinking that every time you use die1 or any of the other die variables, that it is re-executing the code at the top of your file, but it doesn't.
The code at the top of your file is executed only once and then the value stored in that variable is used for the rest of the program execution. Until you change it. So you would want something more like this:
//Getting the die roll if the player chooses the 24 sided die
if (diechoice.equals ("1")) {
die1 = rn1.nextInt(range1) + minimum1;
System.out.println("Player rolled a " + die1);
System.out.println("Player moves forward " + die1 +" spaces");
p1+=die1;
}
You would also need to change that in the other cases where the die is rolled.
Another benefit to doing it this way is that you really only need one random number generator. You don't actually need one for each die. You can use the same one for all die rolls.
Problem number 2:
I'm not sure exactly what is going wrong with die rolls, if there really is something going wrong there, but I did notice a few places where you'll want to change what is done to p1 and p2:
When the player gets a card that moves them ahead, you'll want to use += instead of =. i.e. p1 += cardmove5 instead of p1 = cardmove5
When the player gets a card that moves them back, it looks like you forgot to add the p1 -= cardmove statements.
Also, make sure you have p1 and p2 in the right places. For example, I'm thinking that on the computer's turn, if they get the card to move them to the other player's spot, you meant to do p2 = p1, but instead you have p1 = p2. Same with the computer going back to 0. You have p1 = 0, but it seems like you would want p2 = 0. So just be careful about that. (Also be careful about copy paste. I'm guessing that's why that happened)
Problem number 3:
This problem looks like it's caused by the fact that you are using the || operator where you should be using &&. When you use ||, you are effectively saying "or". So this first statement
if (spacesmoved >= (83) || spacesmoved <= (89))
reads as "if spacesmoved is greater than or equal to 83 OR less than or equal to 89"... Think about that for a second. Is there any number that is NOT greater than 83 OR less than 89? The answer is no. EVERY number will satisfy this condition. You would want to use &&, which means "and" like this:
if (spacesmoved >= (83) && spacesmoved <= (89))
"if spacesmoved is greater than or equal to 83 AND less than or equal to 89", which would only work for numbers between 83 to 89 inclusive.
You will also want to remove the semicolons after your "if" statements in that block and the other similar blocks. If you don't, the code inside those conditions won't get executed. That's actually a really tough bug to find when it happens.
Another thing to know is that when you want multiple things to be executed in an "if" condition, you must enclose it in curly braces {}, otherwise, only the first line will be included in the condition, and any following lines will be executed unconditionally. That is another fact that is causing this third problem.
One last thing is that you should try using "else if" and "else" statements. It will help your code flow make more sense. I'm not going to do all the work for you, but this code block should probably look more like this:
if (p1 >= (83) && p1 <= (89))
{
p1 = (82);
System.out.println("Player landed in a lake, player goes back to space " + p1);
}
else if (p1 >= (152) && p1 <= (155))
{
p1 = (151);
System.out.println("Player landed in a lake, player goes back to space " + p1);
}
else if (p1 >= (201) && p1 <= (233))
{
spacesmoved = (spacesmoved / 2);
p1 -= spacesmoved;
System.out.println("Player landed in mud, players turns are cut in half until player gets out");
}
Bonus Tip
You're learning well, and it seems you are thinking of code flow pretty well. Just keep working and learning and you'll get it.
Look into your usage of parentheses. Using them doesn't hurt anything, but you are using them WAY more than you need.
Good luck! And keep learning!

Loop with Dice rolling program, previous roll and double check

A fairly trivial problem to most I am sure but I can't quite work out how I'm meant to get the previous dice integer to remain the same as the previous roll of die in the program. I think the code is fairly self explanatory and this is such a trivial program I'm kicking myself for not being able to get my head around it.
import java.util.Random;
public class Dice {
public static void main(String[] args) {
Random rand = new Random();
int min = 1;
int max = 6;
int loop = 0;
int diceRollOne = 0;
int diceRollTwo = 0;
int diceTotal = 0;
int prevDiceTotal = 0;
while (loop < 15000) {
loop++;
diceRollOne = rand.nextInt(max - min + 1) + min;
diceRollTwo = rand.nextInt(max - min + 1) + min;
diceTotal = diceRollOne + diceRollTwo;
System.out.println("Dice Roll 1: " + diceRollOne);
System.out.println("Dice Roll 2: " + diceRollTwo);
System.out.println("Dice Total: " + diceTotal);
System.out.println("previous total: " + prevDiceTotal);
prevDiceTotal = diceTotal;
if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
System.out.println("After " + loop + " loops the");
System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
System.exit(0);
}
}
}
}
The basic idea being 15,000 simulations. Roll two dice. If you roll a double quit. If you roll the same sum in the current roll as the sum of the previous roll then quit. I've tried debugging by printing out the previous dice total but it defaults to zero every time.
You just want to move the prevDiceTotal = diceTotal; to after your if statement.
if (diceRollOne == diceRollTwo || diceTotal == prevDiceTotal) {
System.out.println("After " + loop + " loops the");
System.out.println("Numbers Match, YOU GET NOTHING, YOU LOSE, GOOD DAY SIR!");
System.exit(0);
}
prevDiceTotal = diceTotal;
You have the following:
prevDiceTotal = diceTotal;
if(diceRollOne == diceRollTwo || diceTotal == prevDiceTotal){
As it's written now it guarantees if-expression to be True.
Move the assignment after your if block.
This is where a good IDE can help you. Here is what IntelliJ IDEA (which has a free Community Edition) shows for your code. Note the highlighting of the if() statement along with a description of the problem.
As others have said, move the assignment of prevDiceTotal after the if() block to solve the problem.

Need assistance with Min and Max function?

I have an application a number guess game, users have to guess a number between 0 and 100, when they guess right the program asks them if they would like to play again when their done play I display the least number of guesses in a game and the greatest number of guess in a game. Right now all i get is the sum of all their guesses in the when using the "Math.min(,)"?
How do I get the minimum function to work??? the function code is in further below.
leastNumGuesses = Math.min(leastNumGuesses,guesses);
double rightNum = Math.random() *100;
int randomNum = (int) rightNum; //convert the random number to int
int tries = 0; //single game gussess output
int numberOfGames = 0;
int allTries = 0; //accumalates all tries(sum of all tries)
int guesses = 0; // guesses of all games combined
int gameGuesses = 0;
int leastNumGuesses = 100;
int mostNumGuesses = 0;
while (choice.equalsIgnoreCase("y"))
{
System.out.println();
int guess = getIntWithinRange(sc,"Enter the Number: ", 0, 100);
tries++;
guesses++;
gameGuesses++;
if (guess == randomNum)
{
numberOfGames++;
System.out.println("You got it in " + tries + " tries.");
leastNumGuesses = Math.min(leastNumGuesses,gameGuesses);
if (tries <=3)
System.out.println("Great work! You are a mathematical wizard.");
else if (tries > 3 && tries <= 7)
System.out.println("Not too bad! You've got some potential.");
else if (tries > 7)
System.out.println("What took you so long? Maybe you should take some lessons.");
System.out.println();
System.out.println("Would you like to play again (y/n):");
choice = sc.nextLine();
while (!choice.equalsIgnoreCase("n") && !choice.equalsIgnoreCase("y"))
{
System.out.println("Error! entry must be \"y\" or \"n\".");
System.out.println("Would you like to play again (y/n):");
choice = sc.nextLine();
}
if (choice.equalsIgnoreCase("y"))
{ // reset the random number & tries
rightNum = Math.random() *100;
randomNum = (int) rightNum;
tries=0;
gameGuesses++;
}
else if (choice.equalsIgnoreCase("n"))
{
allTries += guesses;
int averageNumGuess = allTries / numberOfGames;
System.out.println("Bye - Come back again");
System.out.println("Number of Games Played: " + numberOfGames);
System.out.println("Average Number of Guesses: " + averageNumGuess);
System.out.println("Least Amount of Guesses In a Single Game: " + leastNumGuesses);
}
}
It seems that you're changing what you want guesses to stand for in the middle of the program.
Remember that guesses is the total number of guesses over all games played, and that leastNumGuesses is initially set to 100. In most cases, you will find that guesses < leastNumGuesses, and thus the Math.min(guesses, leastNumGuesses) function will return guesses.
To fix: use variable other than guesses, for example, gameGuesses to keep track of how many guesses were made in a game. Then, Math.min(,) will behave as you expect.

Categories