【问题标题】:Fill an array with random numbers android/ java用随机数填充数组 android/java
【发布时间】:2011-11-29 03:10:41
【问题描述】:

我在执行以下操作时遇到了麻烦,不知道该怎么做:我想填充一个使用随机数 (1-40) 生成的数组,并使其不会重复。另外,有没有办法让数组自己使用下一个值。所以假设我有测试[1] =“3”,然后测试[2] =“6”。有没有办法让它进入下一个值而不是调用 test [2]?

非常感谢

【问题讨论】:

标签: java android arrays random int


【解决方案1】:
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 40;)
{
    int rand = ((int)(Math.random() * 40)) + 1;
    if(!list.contains(rand))
    {
        list.add(rand);
        i++;
    }
}

或:

List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 40; i++) list.add(i);
Collections.shuffle(list);

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 2011-01-23
    • 1970-01-01
    • 2017-06-04
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多