Reputation: 591
I'm new to programming java and i need to make random integers between 2 values. I could not find any relevant info in the oracle tutorials.
because i'm new to java, most of what i researched i don't understand. I have looked at the following:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
Generating a Random Number between 1 and 10 Java
http://www.javapractices.com/topic/TopicAction.do?Id=62
How do I generate random integers within a specific range in Java?
Getting random numbers in Java
i have tried:
import java.util.Random;
public static void main(String[] args) {
Random randint = new Random();
System.out.println(randint);
result:
java.util.Random@52e922
it appears to be printing the type of randint
.
so, how do i create a random integer between 2 values, and then print the result to the screen?
Upvotes: 2
Views: 16582
Reputation: 21
It functions to me, the possible results includes the max value but not the min.
int random = (int)(Math.random() * (max - min) + 1) + min
Upvotes: 0
Reputation: 1337
You can specify the range of the random number like this:
Random random = new Random();
int min = 2;
int max = 5;
int x = random.nextInt((max-min)+1) + min;
The number that will be generated will be between 2 and 5.
If you do not need to specify any range then you can do it like this:
Random random = new Random();
int x = random.nextInt(11);
Note that the random number in this example will be between 0 and 10.
In either case, You will need to include the following import statement to your program as long as you want to use the Random class.
import java.util.Random;
Upvotes: 1
Reputation: 3180
If you want a value between two integer values (min and max) Here you go:
Random r = new Random();
int randInt = r.nextInt(max-min) + min;
System.out.println(randInt);
So max would be 5 and min would be 2 if you want a integer between 2 and 5
Upvotes: 4
Reputation: 67900
You are printing the Random
object. You need to use a function of the object to get a random integer:
Random random = new Random();
int i = random.nextInt(2);
System.out.println("Random value: " + i);
Upvotes: 0
Reputation: 27
You need to make a int or something to store them in
Random randint = new Random();
int a = randint.nextInt(2)+1;
System.out.print(a);
Do note however I use +1 because java always counts from 0. So this will produce 1 or 2.
Upvotes: 0