This Random class, which can generate random numbers of various data types, here we mainly introduce the way to generate integers and decimals.
1 Method introduction 2 public int nextInt( int maxValue) Generate random integers in the range of [ 0 , maxValue), including 0, excluding maxValue; 3 public double nextDouble() Generate random decimals in the range of [ 0 , 1 ), including 0. 0 , excluding 1. 0 .
1 How to use Random: 2 Import package: the package java.util.Random belongs to 3 Create instance format: Random variable name = new Random();
RandomDemo.java code demo:
1 /* 2 The existing reference type Random class in java, function, generate random numbers 3 steps: 4 1. Import the package, Random class, also in the java.util folder5 2. Formula: Create a variable of type Random6 3. Variables. Call the function in the Random class to generate a random number 7 8 Random class provides a function, the name nextInt() generates a random number, the result is the range of random numbers in the int type 9 , in the function nextInt (write an integer) , Integer: Random number in the range of 10. The range of random numbers is between 0 - the specified integer nextInt(100) [0,99) 11 12 The random number generated by floating point: function name nextDouble() The range of random numbers [0.0,1.0) 13 14 Random number: pseudo-random number, generated by the virtual machine according to an algorithm written by a human. 15 */ 16 import java.util.Random; 17 public class RandomDemo{ 18 public static void main(String[] args){ 19 // 2. Formula: create a variable of type Random 20 Random ran = new Random(); 21 // 3. Variable. Call the Random class Function to generate random numbers 22 // In the Random class, the function to generate random numbers 23 int i = ran.nextInt(100 ); 24 System.out.println(i); 25 // Problem? Generate random numbers, range 1 26 between -100 // nextInt(100) 0-99 + 1 27 28 double d = ran.nextDouble(); 29 System.out.println(d); 30 } 31 }
Here we focus on generating random numbers in a specified range:
int ranNumber =ran.nextInt(max - min + 1) + min; // ranNumber will be assigned a random number in the range of min and max [min,max]
// Generate random numbers within the specified range in java // int ranNumber =ran.nextInt(max - min + 1) + min; // ranNumber will be assigned a random number within the range of min and max [min,max] // For example: generate a random number between [155,658] int ranNumber = ran.nextInt(504) + 155 ; System.out.println(ranNumber);