Java gets a random number within a certain range

1. Mold taking operation

Copy code
public static void main(String[] args){
  for (int i = 1; i <= 20; i++){
    int j = i % 11;
    System.out.println(i + "The result of %11——" + j);
  }
}
/*
The result of 1%11——1
The result of 2%11——2
The result of 3%11——3
The result of 4%11 - 4
The result of 5%11 - 5
The result of 6%11 - 6
The result of 7%11 - 7
The result of 8%11 - 8
The result of 9%11 - 9
The result of 10%11 - 10
The result of 11%11——0
The result of 12%11——1
The result of 13%11 - 2
14%11 results - 3
The result of 15%11 - 4
16%11 results - 5
The result of 17%11 - 6
18%11 results - 7
19%11 results - 8
The result of 20%11 - 9
*/
Copy code

二、java.uitl.Random

random.nextInt(20), any integer between [0,20), 0 can be obtained, but 20 cannot be obtained.

3. Take any number within a certain range

Copy code
public static String getRandom(int min, int max){
    Random random = new Random();
    int s = random.nextInt(max) % (max - min + 1) + min;
    return String.valueOf(s);

}

/*
Principle: The range of the random number to be obtained is [2,100]. Assume that the range of the returned pseudo-random number is [0,N), that is, [0,N-1]; modulo 99 for the obtained number, so the calculation is The range of the number is [0,98]; add 2 to the result, and the range is [2,100].
*/
Copy code

 


Guess you like

Origin blog.csdn.net/dhklsl/article/details/80647950