How to use random.nextInt() and Math.random() in Java?

In Java, you can generate random numbers using the Random class or the Math.random() method.

  1. Unpredictable
  2. generate a random integer
import java.util.Random;

Random random = new Random();
int randomNumber = random.nextInt(100); // 生成一个0到99之间的随机整数
  1. Generate a random number in JavaScript using the Math.random() function.
double randomDouble = Math.random(); // 生成一个0到1之间的随机双精度浮点数
int randomNumber = (int) (Math.random() * 100); // 生成一个0到99之间的随机整数

It should be noted that the Math.random() method generates a random double-precision floating point number between 0 and 1. If you need to generate an integer type random number, you will need to multiply it by a range value and perform a type conversion. However, the Random class’s nextInt() method can directly generate integers within a specified range.

Leave a Reply 0

Your email address will not be published. Required fields are marked *