jeudi 1 octobre 2015

Generating random numbers within a range in Java

I can't figure out how to generate random values within a range, I don't think what I'm doing now in my code will ever generate the floor value

 public static void main(String[] args) 

{

  int rand1;
  int rand2;
  int rand3;
  double rand4; 


  Random r = new Random();
  // Part A: Generate random integer number between 30 and 50 (inclusive) 
  rand1 = 30 + r.nextInt(50-30) + 1;     
  // Part B: Generate random integer number between 20 and -20 (inclusive) 
  rand2 = -20 + r.nextInt(20-(-20)) + 1;  
  // Part C: Generate random integer number between -20 and -60 (inclusive) 
  rand3 = -60 + r.nextInt(-20-(-60)) + 1;
  // Part D: Generate random integer number between 0.0 and 15.9999 (inclusive) 
  rand4 = 0.0 + (15.9999 - 0.0) * r.nextDouble();;



  /******************************************************************************
  *                              Outputs Section                                *
  ******************************************************************************/
  System.out.println("A random integer number between 30 and 50 (inclusive): " + rand1);
  System.out.println("A random integer number between 20 and -20 (inclusive): " + rand2);
  System.out.println("A random integer number between -20 and -60 (inclusive): " + rand3);
  System.out.println("A random integer number between 0.0 and 15.9999 (inclusive): " + rand4);




Aucun commentaire:

Enregistrer un commentaire