No repeating random number in loop - java

I am beginner in Java, Now, I am trying to create the Guess Game in computerized player. I'm ASL fluent, Please forgive me if I make a poorly grammar in english. I will do my best to make this clear.
I am trying to stop a repeating random number from integer. I used arraylist to make a random from list, seem random still pick up the same value, I thought random won't have same value. I used Collections.shuffle, but it only works in array. I used arraylist contains, but it require to have at least one array to make a true or false, it can't determined the true and false when array is empty when java is run in beginning.
Please anyone can help me to stop this repeat? Thank you in advance time.
This "int a" is from other class file (it is a Math.random).
public class GameGuess extends Thread {
int a;
public void Send(int a) {
this.a = a;
ArrayList myArray = new ArrayList();
ArrayList secArray = new ArrayList();
Random rand = new Random();
int p1;
int p2;
do {
p1 = (rand.nextInt(60 - 50) + 50);
p2 = (rand.nextInt(60 - 50) + 50);
myArray.add(p1);
secArray.add(p2);
System.out.println("Player 1: " + p1);
System.out.println("Player 2: " + p2);
if (p1 == a && p2 == a) {
System.out.println("Both Player1 and 2 are tied!");
break;
}
if (p1 == a) {
System.out.println("Player 1 wins!");
}
if (p2 == a) {
System.out.println("Player 2 wins!");
}
if (p1 != a && p2 != a) {
System.out.println("No one win, try again!");
}
} while (p1 != a && p2 != a);
System.out.println("Player 1 picked: " + myArray);
System.out.println("Player 2 picked: " + secArray);
System.out.println("The secret number is " + a);
}
}

Use a Set to reject random guesses that have already been tried. A Set will be a tiny bit more efficient than a List, but more importantly, it will make clear to anyone reading your code that each element in the collection can occur only once. This makes your code more clear.
Set<Integer> p1Guesses = new LinkedHashSet();
Set<Integer> p2Guesses = new LinkedHashSet();
int p1, p2;
do {
p1 = rand.nextInt(10) + 50;
while (!p1Guesses.add(p1))
p1 = rand.nextInt(10) + 50;
p2 = rand.nextInt(10) + 50;
while (!p2Guesses.add(p2))
p2 = rand.nextInt(10) + 50;
...
By using LinkedHashSet, the order of guesses will be recorded. The add() method of Set returns false if the added element already exists in the set, so that condition can control the loop.
Alternatively, you can add all the numbers in the range to a list, and shuffle it. But if you want to print the guesses that have been tried, it will change the logic a little bit. Essentially, you'd need to find the index of a in each shuffled list. Whichever is lower wins. You could print a sub-list of each string of guesses from zero to its respective correct index.

You could generate a new random number if the player has already had that:
ArrayList myArray = new ArrayList();
ArrayList secArray = new ArrayList();
Random rand = new Random();
int p1;
int p2;
do {
p1 = (rand.nextInt(60 - 50) + 50);
while (myArray.contains(p1))
{
p1 = (rand.nextInt(60 - 50) + 50);
}
p2 = (rand.nextInt(60 - 50) + 50);
while (secArray.contains(p2))
{
p2 = (rand.nextInt(60 - 50) + 50);
}
myArray.add(p1);
secArray.add(p2);

You can upgrade you condition with limitation for iteration. For example,
int maxGame = 100;
int i = 0;
do {
p1 = (rand.nextInt(60 - 50) + 50);
p2 = (rand.nextInt(60 - 50) + 50);
...
i++;
} while (i<maxGame && p1 != a && p2 != a);

Related

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!

Need help on arraylist bound (Homework)

Remove 2 beans from the bag.
If:
They are both black return one of them to the bag and discard
the other.
One is black and the other white return the white bean to the bag
and discard the black bean
Both are white discard both and put a black bean in the bag
What color is the last bean?
You decide to write a program that you can run for 50 simulations.
Start with a bag of 10 beans and continue running the program
incrementing the number of beans in the bag by one until you have
tested for a bag with 60 beans. Fill the bag with random colors of
beans and with draw the beans from the bag on a random basis, as well.
Run the simulation and print out four columns of numbers:
Number of beans
Number of Black Beans
Number of White Beans
Color of last bean.
Use the ArrayList Class to implement this program. Remove beans from
random positions within the array and add beans back in a different
random position
Here's What I have done so far:
but it keeps saying that the arraylist is out of bound. I know where the problem is but I don't know how to fix it. If I remove the plus 1 from the line
index1 = rand.nextInt(bag.size() + 1)
it would say negative bound error.
import java.io.*;
import java.util.*;
import java.util.Random;
public class Counter
{
public static void main (String args[])
{
ArrayList<Integer> bag = new ArrayList<Integer>();
Random rand = new Random();
int color;
int index1;
int index2;
int blackCount = 0;
int whiteCount = 0;
String last = "";
System.out.println("Beans Black White Last");
for (int total = 10; total <= 60; total++)
{
for (int run = total; run > 0; run--)
{
// 1 black and 2 white
color = rand.nextInt(2) + 1;
if (color == 1)
{
blackCount++;
}
else if (color == 2)
{
whiteCount++;
}
bag.add(rand.nextInt(bag.size() + 1), color);
}
System.out.print(total + "\t " + blackCount + "\t " + whiteCount + "\t ");
while (blackCount != 1 || whiteCount != 1)
{
index1 = rand.nextInt(bag.size());
index2 = rand.nextInt(bag.size());
if (bag.get(index1) == 1 && bag.get(index2) == 1)
{
bag.remove(index2);
blackCount--;
}
else if (bag.get(index1) == 1 && bag.get(index2) == 2)
{
bag.remove(index1);
blackCount--;
}
else if (bag.get(index1) == 2 && bag.get(index2) == 1)
{
bag.remove(index2);
blackCount--;
}
else if (bag.get(index1) == 2 && bag.get(index2) == 2)
{
bag.remove(index1);
index2 = rand.nextInt(bag.size());
while (bag.get(index2) == 1)
{
if (bag.get(index2) == 1)
{
index2 = rand.nextInt(bag.size());
}
}
bag.remove(index2);
bag.add(rand.nextInt(bag.size() + 1), 1);
blackCount++;
whiteCount -= 2;
}
}
if (whiteCount == 1)
{
last = "White";
}
else
{
last = "Black";
}
System.out.print(last + "\n");
bag.clear();
blackCount = 0;
whiteCount = 0;
}
}
}

Head First Java: Target Random number is always zero [duplicate]

This question already has answers here:
math.random, only generating a 0?
(4 answers)
Closed 8 years ago.
I have been trying this code and the target number generated using math.random() always comes out to be zero. Is there any problem with the code? Please help. I tried a number of times, but every time i try the target random number is always zero.
public class Player {
int number;
public void guess()
{
number = (int) (Math.random()*10);
}
}
public class GuessGame {
Player p1;
Player p2;
Player p3;
public void startGame()
{
p1 = new Player();
p2 = new Player();
p3 = new Player();
int targetNumber;
targetNumber = (int) Math.random() * 10 ;
System.out.println("The target number is "+ targetNumber);
while(true)
{
p1.guess();
p2.guess();
p3.guess();
int guessp1 = p1.number;
int guessp2 = p2.number;
int guessp3 = p3.number;
System.out.println("Number guessed by player p1 is "+ guessp1);
System.out.println("Number guessed by player p2 is "+ guessp2);
System.out.println("Number guessed by player p3 is "+ guessp3);
boolean isp1 = false;
boolean isp2 = false;
boolean isp3 = false;
if(targetNumber==guessp1)
isp1 = true;
if(targetNumber==guessp2)
isp2 = true;
if(targetNumber==guessp3)
isp3 = true;
if(isp1||isp2||isp3)
{
System.out.println("player1 got it right? " + isp1);
System.out.println("player2 got it right? " + isp2);
System.out.println("player3 got it right? " + isp3);
System.out.println("Game Over!!!");
break;
}
else
{
System.out.println("All Wrong!! Play Again..");
}
}
}
}
public class GameLauncher {
public static void main(String[] args)
{
GuessGame game = new GuessGame();
game.startGame();
}
}
The problem is at below line
targetNumber = (int) Math.random() * 10 ;
Math.random() returns double value between 0 (including) to 1 (excluding) and you are casting that to int that becomes it zero before multiplication.
use
targetNumber = (int) (Math.random() * 10 );
or better use
Random random = new Random();
number = random.nextInt(10);
Due to operator precedence the cast occurs first making the first term in the assigned expression equal to 0 (since Math.random returns a value < 0). You can use parenthesis to multiply the numbers first
targetNumber = (int) (Math.random() * 10) ;
or as Boris said simply use nextInt from the java.util.Random
You should write
targetNumber = (int) (Math.random()*10)
This is because what you are doing converts Math.random() generated number to int as zero and then mulyiplied by 10
You are using Math.random() which states
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
You are casting the result to an int, which returns the integer part of the value, thus 0.
Then 1 + 0 - 1 = 0.
targetNumber = (int) (Math.random() * 10) ;
Consider using Random
Random random = new Random();
number = random.nextInt(10);
Use Random class to generate radom numbers:
Try following code:
int targetNumber;
targetNumber = new Random().nextInt(100) ;

Program using loops and random generator (beginning java)

A drunkard in a grid of streets randomly picks one of four directions and stumbles to the next intersection, then again randomly picks one of four directions, and so on. You might think that on average the drunkard doesn't move very far because the choices cancel each other out, but that is not the case. Represent locations as integer pairs (x,y). Implement the drunkard's walk over 100 intersections, starting at (0,0) and print the ending location
Can anyone help? I'm completely lost with using random generators and loops in the same program
Below is what I have. It complies fine but doesn't print anything and I'm not sure if I got the random 100 intersection thing right
import java.util.*;
class Drunkard {
int x, y;
Drunkard(int x, int y) {
this.x = x;
this.y = y;
}
void moveNorth() {
this.y -= 1;
}
void moveEast() {
this.x += 1;
}
void report() {
System.out.println("Hiccup: " + x + ", " + y);
}
}
class Four {
public static void main(String[] args) {
Random generator = new Random();
Drunkard drunkard = new Drunkard(100, 100);
int direction;
for (int i = 0; i < 100; i++) {
direction = Math.abs(generator.nextInt()) % 4;
if (direction == 0) { // N
drunkard.moveNorth();
} else if (direction == 1) { // E
drunkard.moveEast();
} else if (direction == 2) { // S
System.out.println("Should move South.");
} else if (direction == 3) { // W
System.out.println("Should move West.");
} else {
System.out.println("Impossible!");
}
System.out.drunkard.report();
}
}
}
your program will be:
initialization
loop: for 1 to 100, do:
i = random()
if i<=0.25 : go north
if i>0.25 and i<=0.5 : go south
if i>0.5 and i<= 0.75 : go east
if i>0.75 and i<= 1 : go west
end loop
show final point.
I see a variety of problems:
You are initializing your Drunkard's position to 100,100. The assignment said to initialize to 0,0.
System.out.drunkard.report() absolutely does not compile. Just call drunkard.report().
The instructions say to print the final location, so you need to move the call to drunkard.report() down one line, so that it is outside of the for loop.
You haven't written methods for moveSouth or moveWest. Write them and add calls to them in the appropriate place.
The class Four needs to be public in order to run it directly.
Good Java programming practices say that every class should be in its own file, but this probably goes against what your instructor asked you to do.
But, I don't think that's your problem. I think there's a problem with how/where you're trying to run the program. You say it compiles fine but doesn't print any output. You know that after it compiles there is another step to run the program, right?
To be clear, here's what you should be doing. At a command line, make sure you are in the directory where your .java file lives. I'm going to assume it's called Four.java. Type the following, hitting enter after each line. (Don't type the $ prompt)
$ javac *.java
$ java Four
I copied the code you posted above, fixed the problems I highlighted, and followed my own instructions above; it works perfectly.
You can use
int direction = (new Random()).nextInt(4);
And use this direction variable to determine where he walks to. I would use recursion in this case instead of a loop.
This starts at 0,0. Generates a random number to determine location and updates the location.
Not sure about the way you are generating the random number, this seems to work well for me.
Point currentLocation = new Point();
currentLocation.setLocation(0, 0);
Point newLocation = new Point(0,0);
Random random = new Random();
//make 100 moves
for(int i=0; i<100; i++)
{
int k = random.nextInt(4);
if(k == 0)
{
//use your drunkard method here
newLocation.setLocation(currentLocation.getX(), currentLocation.getY() + 5);
}
else if (k == 1)
{
//go south
newLocation.setLocation(currentLocation.getX(), currentLocation.getY() - 5);
}
else if (k == 2)
{
//go east
newLocation.setLocation(currentLocation.getX() + 5, currentLocation.getY());
}
else if(k == 3)
{
//go west
newLocation.setLocation(currentLocation.getX() - 5, currentLocation.getY());
}
currentLocation.setLocation(newLocation);
}
System.out.println(currentLocation);
}
You're not implementing your random generator to its full extent.
Random generator = new Random();
int direction = generator.nextInt(4); // This will return a random int
// between 0 and 3
Some other useful tricks when using Random() are as follows:
int i = generator.nextInt(4)+2; // This will return a random int
// between 2 and 5
I highly recommend you check out this if you'd really like to learn all of the neat tricks that you can do using the Random Class.
All i did for this is create a loop that generated a random number between -1 and 1, and summed the values 100 times. Do that for x and for y.
int x = 0;
int y = 0;
//intial = (0,0)
//North = (0, 1)
//South = (0, -1)
//East = (1, 0)
//West = (-1, 0)
for(int i = 0; i < 100; i++)
{
x += (int) (Math.random() * 3) + (-1);
y += (int) (Math.random() * 3) + (-1);
}
System.out.printf("The Drunkard is now located at: (%d, %d)", x, y);

Categories