How do I write a program in java to generate random numbers between 1 and 2 ? Do I need to use for-loop or math.random ?? Is there any calculations that needs to be done before writing the code ?
Asked
Active
Viewed 165 times
-2
-
2possible duplicate of [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) – Jordi Castilla Nov 19 '14 at 10:25
-
Check this link ( Generate Random Number using java) http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java... you can also check http://java.about.com/od/javautil/a/randomnumbers.htm – MAK Nov 19 '14 at 10:28
2 Answers
1
You might want to take a look at java.util.Random, which does much of the work for you, especially the method nextFloat
. Since this returns float
s between 0.0 and 1.0, just add 1 to the result to get float
s between 1.0 and 2.0
You might also want to take a look at this question, which asks the same thing, just with a different range.

Community
- 1
- 1

Alexander Weinert
- 665
- 4
- 12
0
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
public static final void main(String... aArgs){
log("Generating 10 random integers in range 0..99.");
//note a single Random object is reused here
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}
log("Done.");
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}

JavaDeveloper
- 39
- 6