How to generate a random integer using math.random class [duplicate] - java

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 7 years ago.
I am having trouble with the RandInt() method as it will not return a random integer. The result must be an int ranged 0-9 and must use the math.random class. This is my code below:
public class RandNumGenerator {
public static int RandInt() {
int n = (int) Math.random() * 10;
return n;
}
public static void main(String[] args) {
RandInt();
}
}

You should cast the double to int after multiplying by 10 :
int n = (int) (Math.random() * 10);
Otherwise you'll always get 0 (since Math.random()<1.0 and therefore (int)Math.random() is always 0).

Casting has higher priority than * so code
(int) Math.random() * 10;
is same as
((int) Math.random()) * 10;
and since Math.random() returns values in range [0; 1) (1 - excluded) casting to int
(int) Math.random()
will produce 0 which multiplied by 10 will also return 0.
You may want to use
(int) (Math.random() * 10)
or easier to read and maintain Random#nextInt(max) to generate range [0; max) (max-exclusive)

You need to put brackets around the multiplication
int n = (int) (Math.random() * 10);
what's happening is
int n = ((int) Math.random()) * 10;
as Math.random() is always greater or equal to 0 and less than 1, converting it to an integer will always equal zero. Multiplying it by 10 will do nothing.

You shouldn't really be using Math.random() to generate random integers, as it will generate random floats (i.e, decimal numbers)
You should do something similar to this
Random myRandom = new Random();
int randomInt = myRandom.nextInt(10);

Related

Can i create different random numbers in one for loop in java [duplicate]

The following code is only producing a 0 ;-;
What am I doing wrong?
public class RockPaperSci {
public static void main(String[] args) {
//Rock 1
//Paper 2
//Scissors 3
int croll =1+(int)Math.random()*3-1;
System.out.println(croll);
}
}
Edit, Another Poster suggested something that fixed it.
int croll = 1 + (int) (Math.random() * 4 - 1);
Thanks, everyone!
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.
Consider using java.util.Random
Random rand = new Random();
System.out.println(rand.nextInt(3) + 1);
Math.random() generates double values between range - [0.0, 1.0). And then you have typecasted the result to an int:
(int)Math.random() // this will always be `0`
And then multiply by 3 is 0. So, your expression is really:
1 + 0 - 1
I guess you want to put parenthesis like this:
1 + (int)(Math.random() * 3)
Having said that, you should really use Random#nextInt(int) method if you want to generate integer values in some range. It is more efficient than using Math#random().
You can use it like this:
Random rand = new Random();
int croll = 1 + rand.nextInt(3);
See also:
Math.random() versus Random.nextInt(int)
All our mates explained you reasons of unexpected output you got.
Assuming you want generate a random croll
Consider Random for resolution
Random rand= new Random();
double croll = 1 + rand.nextInt() * 3 - 1;
System.out.println(croll);
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
int croll =1+(int)Math.random()*3-1;
eg
int croll =1+0*-1;
System.out.println(croll); // will print always 0

Java random number

Beginner question here:
I tried creating a random number using this code
int rand = (int) Math.random()*10;
however, i kept receiving 0 as the answer when printing to screen
only after putting parenthesis like so
int rand = (int)(Math.random()*10);
did the number show properly.
Can anyone explain the logical reason for this that I missed?
When you write int rand = (int) Math.random()*10, you're actually writing:
int rand = ((int) Math.random()) * 10;
Therefore you get 0 because the random number is between 0 and 1, and casting it to an int makes it equals to 0.
The code
int rand = (int) Math.random()*10;
is equivalent to
int rand = ((int) Math.random()) * 10;
So the value of Math.random() is converted to an int. Because that value is between 0 and 1 (1 excluded) it is converted always to zero.
So
(int) Math.random()*10 --> ((int) Math.random()) * 10 --> 0 * 10 --> 0
Math.random() returns a double number between 0 and 1 exclusive, which means (int)Math.random() will always be 0 (since Math.random() < 1). In order to perform the multiplication before the cast to int, you must use parentheses as you did.
The other answers already explained the issue with your code, so I won't cover this topic here anymore.
This is just a note on the generation of random-numbers:
The recommended way of generating random-numbers in java isn't Math.random() , but via the java.util.Random class (http://docs.oracle.com/javase/7/docs/api/java/util/Random.html).
To generate a random-number like in the above example, you can use this code:
Random rnd = new Random();
int i = rnd.nextInt(10);
, which will produce the same result as your code.
int rand = (int) Math.random()*10;
is equivalent to
int rand = ((int) Math.random())*10;
Considering that Math.random() return a number from 0<=N<1, if you try to cast it you will always get 0, that multiply by 10 is still 0
int rand = ((int) Math.random()); -- ALWAYS --> ZERO
0*N ---- ALWAYS ---> ZERO

Random numbers in Java when working with Android

I need to make a random number between 1 and 20, and based on that number (using "If - Then" statements), I need to set the image of an ImageView.
I know that in Objective-C, it goes like this:
int aNumber = arc4Random() % 20;
if (aNumber == 1) {
[theImageView setImage:theImage];
}
How can I do this in Java? I have seen it done this way, but I do not see how I can set the range of numbers (1-20, 2-7, ect).
int aNumber = (int) Math.random()
Docs are your friends
Random rand = new Random();
int n = rand.nextInt(20); // Gives n such that 0 <= n < 20
Documentation:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
Thus, from this example, we'll have a number between 0 and 19
Math.random() returns an double from [0,1[.
Random.nextInt(int) returns an int from [0, int[.
You can try:
int aNumber = (int) (20 * Math.random()) + 1;
or
Random rand = new Random();
int n = rand.nextInt(20) + 1;
You can use Math.random() to generate a double between 0 and 1 non-inclusive. Android Javadoc here.

Getting random numbers in Java [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 3 years ago.
I would like to get a random value between 1 to 50 in Java.
How may I do that with the help of Math.random();?
How do I bound the values that Math.random() returns?
The first solution is to use the java.util.Random class:
import java.util.Random;
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;
Another solution is using Math.random():
double random = Math.random() * 49 + 1;
or
int random = (int)(Math.random() * 50 + 1);
int max = 50;
int min = 1;
1. Using Math.random()
double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);
This will give you value from 1 to 50 in case of int
or 1.0 (inclusive) to 50.0 (exclusive) in case of double
Why?
random() method returns a random
number between 0.0 and 0.9..., you
multiply it by 50, so upper limit
becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to #rup in comments). leepoint's awesome write-up on both the approaches.
2. Using Random class in Java.
Random rand = new Random();
int value = rand.nextInt(50);
This will give value from 0 to 49.
For 1 to 50: rand.nextInt((max - min) + 1) + min;
Source of some Java Random awesomeness.

How to generate random positive and negative numbers in Java [duplicate]

This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 4 years ago.
I am trying to generate random integers over the range (-32768, 32767) of the primitive data type short. The java Random object only generates positive numbers. How would I go about randomly creating numbers on that interval? Thanks.
You random on (0, 32767+32768) then subtract by 32768
Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);
public static int generatRandomPositiveNegitiveValue(int max , int min) {
//Random rand = new Random();
int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
return ii;
}
Generate numbers between 0 and 65535 then just subtract 32768
This is an old question I know but um....
n=n-(n*2)
([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))
example:
// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));
(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))
In case folks are interested in the double version (note this breaks down if passed MAX_VALUE or MIN_VALUE):
private static final Random generator = new Random();
public static double random(double min, double max) {
return min + (generator.nextDouble() * (max - min));
}

Categories

Resources