-2

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 ?

Amirul
  • 13
  • 1
  • 5
  • 2
    possible 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 Answers2

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 floats between 0.0 and 1.0, just add 1 to the result to get floats 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
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);
  }
}