如何生成Java 6中不同的随机数 [英] How to generate 6 different random numbers in java

查看:240
本文介绍了如何生成Java 6中不同的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用的Math.random产生6种不同的随机数,并将其存储到一个数组。
我怎样才能确保它们有什么不同?我知道我需要使用for循环来检查数组但如何...

I want to generate 6 different random numbers by using Math.random and store them into an array. How can I make sure that they are different? I know I need to use for-loop to check the array but how...

这是该范围内。我只需要1到49之间的数字。
 (1 +(int)的(的Math.random()* 49))

This is the range. I only need numbers between 1 and 49. ( 1 + (int) (Math.random() * 49) )

推荐答案

在Java的8:

final int[] ints = new Random().ints(1, 50).distinct().limit(6).toArray();

在Java 7中:

public static void main(final String[] args) throws Exception {
    final Random random = new Random();
    final Set<Integer> intSet = new HashSet<>();
    while (intSet.size() < 6) {
        intSet.add(random.nextInt(49) + 1);
    }
    final int[] ints = new int[intSet.size()];
    final Iterator<Integer> iter = intSet.iterator();
    for (int i = 0; iter.hasNext(); ++i) {
        ints[i] = iter.next();
    }
    System.out.println(Arrays.toString(ints));
}

只是有点混乱。在事实上,它是pretty繁琐拆箱没有帮助的设置&LT;整数GT; INT []

应当注意的是,这种解决方案应该是细所需值的数目是<强>显著较小比的范围内。由于 1..49 6 你没事大了不少。否则,性能迅速降低。

It should be noted that this solution should be fine of the number of required values is significantly smaller than the range. As 1..49 is quite a lot larger than 6 you're fine. Otherwise performance rapidly degrades.

这篇关于如何生成Java 6中不同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆