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);
Answer from nyanev on Stack OverflowHow do I use java.util.Random to generate random integers within a given interval?
Random number generator
How does one decide between ways to generate a random number in Java?
Question about random numbers in java
Videos
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.
I am trying to generate a random number between 25 and 50, however every time I run my code, I keep getting 35. My teacher says it's because I planted a "seed" inside the Random declaration, but how would I change this into an interval?
import java.util.Random;
public class Range{
public static void main(String[] args) {
`// TODO Auto-generated method stub`
Random rand = new Random(25);
int num = rand.nextInt(51);
System.out.println(num);
}
}
I need to write a program that will generate a number between -20, and 20 for a school project. When attempting to turn it in I get a message stating that I dont have a randomized range from -20 to 20. Is it somethung with my code or just a website error?
My code: import java.lang.Math;
class Lesson_9_Activity_Two {
public static void main(String[] args) {
System.out.println((int)(Math.random()*40)-20);
} }
I looked on the internet for ways to generate a random number in java, and I saw that there's at least three different ways to do it with native packages. Why are there so many? Are there downsides I should look out for or is it safe to just pick between them randomly? (ha)