Java语言学习总结 高级篇 Random库概述及其使用

Random库

概述

Random库主要用来生成随机数字。
Random库中的方法摘要:
方法摘要

使用步骤

三步:导包——创建——使用
代码示例(获取一个随机生产的int数字):

import java.util.Random;
public class TestRandom {
	
	public static void main(String[] args) {
		Random r = new Random();
		int num = r.nextInt();
		System.out.println("随机数:"+num);

	}

}

输出如图:
输出的随机生成整型数字

生成一定范围内的随机数

random的方法nextInt() 可以重载一个参数。参数代表一个范围,是左闭右开区间。例如: int num = r.nextInt(3);
实际上代表的含义是:[0,3) 这样写固定从0开始
代码示例:

import java.util.Random;
public class TestRandom {
	
	public static void main(String[] args) {
		Random r = new Random();
		for(int i = 0; i<10; i++) {
			int num = r.nextInt(10);
			System.out.println(num);
		}

	}

}

这段代码生成一段0~9之间的随机数字,输出结果如图:
生成的数字

指定生成随机数的范围,左右边界都指定

实现代码如下:

import java.util.Random;
public class TestRandom {
	
	public static void main(String[] args) {
		int n = 5;
		Random r = new Random();
		for(int i=0;i<10;i++) {
			int result = r.nextInt(n)+1;
			System.out.println(result);
		}
	}
}

这样就实现了**[1,5]内的随机数字生成。 如果需要生成[10,20],则在resulth后面+1改成+10**, n改成10

——————————————————————

发布了43 篇原创文章 · 获赞 3 · 访问量 4950

猜你喜欢

转载自blog.csdn.net/Ace_bb/article/details/104056388