首页 > 解决方案 > 创建不在数组中的随机数

问题描述

我有许多应该随机选择的开关盒,但每个开关盒只能选择一次。我制作了一个随机生成器和一个用于添加案例的数组,但我卡住了,因为我的代码不太好。这是我目前拥有的

 public void showRandomButton() {
        //Generate Random Numbers
        final int min = 0;
        final int max = 13;  //n-no of random events
        Random g=new Random();
        int random = g.nextInt((max - min) + 1) + min;
        //Random number 0(inclusive)-9(inclusive)

        while(Arrays.asList(list).contains( random )) {
            int numb = g.nextInt((max - min) + 1) + min;
            random = numb;

        }
        switch(random){
            case 1:
                mbutton1.setVisibility( View.VISIBLE );
                mbuttonStart.setVisibility( View.GONE );
                break;
            case 2:
                mbutton2.setVisibility( View.VISIBLE );
                mbuttonStart.setVisibility( View.GONE );
                break;
                //Function 2 break;

谢谢你的帮助

标签: java

解决方案


试试这个:

int min = 0;
int max = 13;  
List<Integer> list = new ArrayList<Integer>();

for(int i = min; i <max;)
{
int rand = ((int)(Math.random() * max)) + 1;
if(!list.contains(rand))
{
    list.add(rand); // it will be added only if not in list
    i++;
}
}

推荐阅读