Java随机数Random类基本使用以及随机数重复问题

可参考官方API:

https://docs.oracle.com/javase/7/docs/api/java/util/Random.html

	@Test
	public void test() {
		Random random = new Random();// 创建新的随机数生成器
		int nextInt = random.nextInt(101);// 生成随机数范围0-100;包含0但不包含101;
	}

随机数有可能会出现重复,正好有个练习题练手顺便解决问题:


	/**
	 * 题目:解决随机数重复问题且结果不能有0 1.定义数组来存储并判断下次存储随机数是否存在 2.不能确定循环几次才能满足结果,循环使用while
	 */
	@Test
	public void test1() {
		Random random = new Random();// 创建新的随机数生成器
		int[] store = new int[5];// 定义数组存储每次生成的随机数
		int index = 0;// 循环终止条件
		while (index < 5) {
			int nextInt = random.nextInt(6);
			if (0 != nextInt && !contains(store, nextInt)) {
				store[index++] = nextInt;// 如果条件成立则将当前随机数字存储到数组中,然后终止条件+1
			}
		}
		ergodic(store);

	}

	/**
	 * 遍历数组判断参数二是否存在
	 */
	public boolean contains(int[] store, int nextInt) {
		for (int i = 0; i < store.length; i++) {// 遍历数组
			if (store[i] == nextInt) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 遍历数组
	 */
	public void ergodic(int[] store) {
		for (int i = 0; i < store.length; i++) {
			System.out.println(store[i]);
		}
	}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值