如何获得要在Java中打印而没有重复的五个随机数的列表?

时间:2014-02-07 03:02:09

标签: java arrays arraylist

我正在尝试根据用户提供的特定范围打印五个永不重复的随机数字。以下是我到目前为止的代码。首先,我不知道如何列出在ArrayList中找到的数字,或者即使我应该只使用ArrayList而不是Array。有什么想法吗?

package h1p2;
import java.util.ArrayList;

public class test{
    public void method (int min, int max){
        //Declare and initialize arrays and index variables
        ArrayList<Integer> rangeOne = new ArrayList<Integer>();
        ArrayList<Integer> rangeMinMax = new ArrayList<Integer>();

        int z = min;
        int i = 0;
        int q = 0;
        //int rangeLength = rangeMinMax.length;

        //need minimum/max differential of 50 or > to execute method
        if (max - min < 50){
            System.out.println("Please enter numbers with a differential of 50 or greater.");
        }

        //run if differential checks out
        else{
            while (z <= max && z >= min ){
                rangeMinMax.set(z, 1);
                i++;    
            }
        }

        while (q < 5){
            int randomNumber = (int)(rangeMinMax.size() * Math.random());
            if (randomNumber == rangeOne.indexOf(0)|| randomNumber == rangeOne.indexOf(1) || 
                    randomNumber == rangeOne.indexOf(2) || randomNumber == rangeOne.indexOf(3) ||
                    randomNumber == rangeOne.indexOf(4) || randomNumber == rangeOne.indexOf(5)){
                break;
            }

            else{
                rangeOne.set(q, randomNumber);
            }

            q++;
        }
        System.out.println("The numbers are " + )
    }
}

1 个答案:

答案 0 :(得分:0)

正如Takendarkk所说,set很有用。

// First check that min, max are valid and far enough apart
Set<Integer> set = new HashSet<>();
Random r = new Random();
while (set.size() < 5) {
    set.add(min + r.nextInt(max - min + 1));
}
System.out.println("Your numbers are: " + set);