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) ;
Related
I am trying to write a simple mastermind game where a 4 digit number will be randomly selected by the computer and the user inputs a number over and over again until the correct number is found. I am trying to do this by passing the guessed number and the random number to their own separate arrays and then comparing them, position by position to see if they are similar. If two numbers are in the exact same spot
Example:
if guessArray[0] == numsArray[0] then the computer will print a *.
If two numbers are present but not in the exact same spot (eg. you made a guess of 2056 but the actual number is 1203) then one + should be printed. This cycle repeats until the number is guessed.
I've already asked a friend in person what the problem was and he couldn't figure it out. He knows the most code out of my friends so this was my next place to go.
Here is the full project. I did not write the ConvertInt2Array method. I found it on the internet.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Mastermind {
public static Random numGen = new Random();
public static void main(String [] args) {
Scanner Input = new Scanner (System.in);
int x = 0;
int number = 0;
int random = 0;
int guess = 0;
int y = 0;
int numArray[] = new int[4];
int guessArray[] = new int[4];
boolean isGuessed = false;
//Generate Random Number
for(x=0; x<=3; x++) {
int rand = Math.abs(numGen.nextInt());//Get the absolute value
random = (rand % 999 + 1);
numArray[x] = random;
number+=random;
}
while(isGuessed == false){
System.out.println("Guess a four digit random number");
guess = Input.nextInt();
guessArray = convertInt2Array(guess);
for(y=0; y<=3; y++) {
if(numArray[y] == guessArray[y]) {
System.out.print("*");
}
else if(Arrays.equals(numArray, y, y, guessArray, 0, guessArray.length) == true) {
System.out.print("+");
}
else {
}
if(guess==number) {
isGuessed = true;
}
}
}
System.out.println("You guessed it correctly!");
}
public static int[] convertInt2Array(int guess) {
String temp = Integer.toString(guess);
String temp2;
int temp3;
int [] gArray = new int[temp.length()];
for(int i=0;i<temp.length();i++) {
if (i!=temp.length()) {
temp2 = temp.substring(i, i+1);
} else {
temp2 = temp.substring(i);
}
temp3 = Integer.parseInt(temp2);
gArray[i] = temp3;
}
return gArray;
}
}
There may be more than one issue here, but here's a potential problem:
int rand = Math.abs(numGen.nextInt()); // Get the absolute value
random = (rand % 999 + 1);
This will usually result in random being a three-digit number. You mentioned you want this to be a four-digit number. Random.nextInt() can return any of the possible 232 integer numbers (from -2147483648 to 2147483647). To fix this, use a different Random.nextInt and specify your bounds:
int lowerBound = 1000;
int upperBound = 10000;
random = numGen.nextInt(upperBound - lowerBound) + lowerBound;
Let's break this down: numGen.nextInt(upperBound - lowerBound) evaluates to numGen.nextInt(9000), which will return a number between 0 (inclusive) and 9000 (exclusive), i.e. anything in the range 0-8999. You then add the lower bound of 1000 to ensure that random will be at least 1000 and up to 9999.
See the documentation for Random.nextInt(int bound).
Hopefully this gets you pointed in the right track.
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 5 years ago.
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:
Generate a random number within a certain range (e.g. 5 through 20).
Take the number and store it within a variable.
Perform arithmetic on it.
Here's the code:
import java.util.HashMap;
public class Attack {
public static void main(String[] args) {
HashMap<String, Integer> attacks = new HashMap<String, Integer>();
attacks.put("Punch", 1);
attacks.put("Uppercut", 3);
attacks.put("Roundhouse Kick", 5);
int actionPoints = // Code for random number generation
System.out.println("A brigade integrant appeared!");
System.out.println("What do you do?");
System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
System.out.println("You have " + actionPoints + " Action Points.");
Scanner reader = new Scanner(System.in);
System.out.println("Enter a number: ");
int n = reader.nextInt();
reader.close();
if n == 1 {
System.out.println("The brigade integrant takes 2 HP of damage!");
}
else if n == 2 {
System.out.println("The brigade integrant takes 5 HP of damage!");
}
else if n == 3 {
System.out.println("The brigade integrant takes 8 HP of damage!");
}
}
}
In Java 1.7+ you can do it in one line (not counting the import statement ;):
import java.util.concurrent.ThreadLocalRandom;
int actionPoints = ThreadLocalRandom.current().nextInt(5, 21); // 5 to 20 inclusive
Try this :
int lower = 12;
int higher = 29;
int random = (int)(Math.random() * (higher-lower)) + lower;
There are multiple options for you to generate a random number. Two of these would be:
Math.random(); // Random values ranging from 0 to 1
Random rand; rand.nextInt(x); // Random int ranging from 0 to x
To specify the exact range you could do something like this:
int RandomNumber = Min + (int)(Math.random() * Max);
I want to generate random integers such that the next generated number is always greater than the previous one.
Assume I start with 3, I want the next to be always greater than 3. And say I generated 5, I want the next to be greater than 5 and so on..
This should get you a number that is consistently larger than the previous value. The range is the maximum distance from the previous value that you want the number to be.
public getLargerRandom(int previousValue){
int range = 100; //set to whatever range you want numbers to have
return random.nextInt(range) + previousValue;
}
int rnd = 0;
while (true) {
rnd = ThreadLocalRandom.current().nextInt(rnd +1, Integer.MAX_INT);
System.out.println("Next random: "+rnd);
}
You would store the randomly generated number as a variable, then use that as a minimum value for the next generation of numbers.
int x = 0;
x = new Random.nextInt(aNumber) + x;
The following example generates a set of random numbers between a start value and a max value without going over the desired maximum number.
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
GetIncreasingInts(20, 3, 101);
}
public static void GetIncreasingInts(int numIntsToGet, int start, int max) {
if (numIntsToGet > 0 && start >= 0 && max > 0) {
Random random = new Random();
int nextStart = start;
int num = -1;
for (int index = 0; index < numIntsToGet; index++) {
if ((max - 1) <= nextStart)
break;
else {
num = nextStart + random.nextInt(max - nextStart);
nextStart = num;
System.out.println("Number: " + num);
}
}
}
}
}
So I wrote this very simple program that asks the user to keep guessing numbers until they guess the correct number, and it will tell them if the number they picked is too low or high. The problem i'm having is the numbers were only supposed to be randomly generated 1 through 100 but java took that as -100 through 100. Anyway I was wondering how to only get it to return positive numbers.
Here is the code:
import java.util.Random;
import java.util.Scanner;
public class GameMain {
public static void main(String[] args) {
int guess = 101;
Random r = new Random();
int answer = r.nextInt()%101;
System.out.println("Whats the number?");
Scanner input = new Scanner(System.in);
while (guess!=answer) {
guess = input.nextInt();
if (guess > answer) {
System.out.println("Too high!");
}
else if (guess < answer){
System.out.println("Too low!");
}
else if (guess == answer){
System.out.println("Correct you win!");
}
}
}
}
The Random class has another nextInt(...) method, one that takes a parameter and that returns a random number between 0 and 1 minus the number passed in. So if you pass in 100, you'll get a pseudo random number between 0 and 99. So just call r.nextInt(100) + 1 on your Random object, r, to get a number between 1 and 100.
In general, if you want a random number between a and b, you would use
r.nextInt(b - a + 1) + a
int answer = Math.abs(r.nextInt());
Not best solution, but another possible alternative...when in doubt with negatives...Math.abs() always works :D
Use
int answer = r.nextInt(100)
instead of
int answer = r.nextInt()%101
Refer this link
http://www.javapractices.com/topic/TopicAction.do?Id=62
you can refer this program and make use i suppose, give 1 as START and 100 as END, generate and then proceed...
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
I am looking for a way to generate a random integer from 0-x, where x is defined at runtime by the human user. However, half of those numbers must be greater than zero and less than or equal to 5 (0,5] and the other half must be in the set of [6,x].
I know that the following code will generate a number from 0-x. The main problem is ensuring that half of them will be in the set of (0,5]
Math.random() * x;
I'm not looking for someone to do this for me, just looking for some hints. Thank you!
You could first flip a coin and based on that generate upper or lower number:
final Random rnd = new Random();
while (true)
System.out.println(rnd.nextBoolean()? rnd.nextInt(6) : 6 + rnd.nextInt(x-5));
Or, using the unwieldy Math.random() (bound to have trouble at the edges of the range):
while (true)
System.out.println(Math.floor(
math.random() < 0.5 ? (Math.random() * 6) : (6 + (x-5) * Math.random())
));
Consider this as a hint only :)
I'd do this:
double halfX= x / 2.0;
double random = Math.random() * x;
if( random< halfX ) {
random = random*5.0/(halfX);
} else {
random = (random/halfX - 1) * (x-5.0) + 5.0 ;
}
I think it is good now. This is less understandable and readable, but has only one call to random for each invocation. Apart from the fact MarkoTopolnic pointed out: the user needed an integer... I'd have to calculate what rounding would do to the distribution.
This is absolutely not easy... My head aches, so the best I can come up with:
double halfX= x / 2.0 + 1.0;
double random = Math.random() * (x+2.0);
int randomInt;
if( random< halfX ) {
randomInt = (int) (random*6.0/(halfX)); //truncating, means equal distribution from 0-5
} else {
randomInt = (int) ((random/halfX - 1.0) * (x-5.0) + 6.0) ; //notice x-5.0, this range before truncation is actually from 6.0 to x+1.0, after truncating it gets to [6;x], as this is integer
}
The second part I'm not sure though... A few hours of sleep would get it right... I hope the intentions and logic is clear though...
In case anyone is curious, here's the solution I came up with based on Marko's solution.
I had the following class defined for another part of this program.
public class BooleanSource
{
private double probability;
BooleanSource(double p) throws IllegalArgumentException
{
if(p < 0.0)
throw new IllegalArgumentException("Probability too small");
if(p > 1.0)
throw new IllegalArgumentException("Probability too large");
probability = p;
}
public boolean occurs()
{
return (Math.random() < probability);
}
}
With that, I did the following
private static void setNumItems(Customer c, int maxItems)
{
BooleanSource numProb = new BooleanSource(0.5);
int numItems;
if(numProb.occurs())
{
double num = (Math.random()*4)+1;
numItems = (int) Math.round(num);
}
else
{
double num = 5 + (maxItems-5)*Math.random();
numItems = (int) Math.round(num);
}
c.setNumItems(numItems);
}