How to use the nextInt() function of the Random class in Java to generate random integers
Introduction:
In programming, we often encounter the need to generate random integers. Java provides the Random class to help us achieve this function. The nextInt() function can generate a random integer within a specified range. This article will introduce readers to how to use the nextInt() function of the Random class to generate random integers and give corresponding code examples.
import java.util.Random; public class RandomExample { public static void main(String[] args) { // 创建一个 Random 类的实例 Random random = new Random(); // 生成一个范围在 -100 到 100 之间的随机整数 int randomInt1 = random.nextInt(201) - 100; System.out.println("随机整数1:" + randomInt1); // 生成一个大于等于 0 小于 100 的随机整数 int randomInt2 = random.nextInt(100); System.out.println("随机整数2:" + randomInt2); // 生成一个范围在 1 到 6 之间的随机整数,模拟掷骰子 int randomInt3 = random.nextInt(6) + 1; System.out.println("随机整数3:" + randomInt3); } }
Summary:
This article introduces readers to how to use the nextInt() function of Java's Random class to generate random integers. After reading this article, readers should have a certain understanding of the basic usage of the Random class and be able to use the nextInt() function in their own code to generate random integers as needed. I hope this article can be helpful to readers.
The above is the detailed content of How to generate random integers in Java using nextInt() function of Random class. For more information, please follow other related articles on the PHP Chinese website!