mardi 12 janvier 2016

Generating Random Numbers Struck in Loop

I am now writing a JAVA program to produce 10 distinct random numbers between 100 and a random number less than 100 (inclusive) and display them in sorted order. Here is the code I wrote

Random rnd = new Random();
ArrayList<Integer> rndNums = new ArrayList<Integer>(10);
int max = 0;
while(rndNums.size() < 10) {
    if(rndNums.size() == 0)
        max = rnd.nextInt(101);
    int num = rnd.nextInt(101);
    if(num >= max || rndNums.contains(num))
        continue;
    rndNums.add(num);
}   
Collections.sort(rndNums);
for(int i : rndNums)
    System.out.println (i);

But the program sometimes struck in loop. I can’t find what the fault that cause is. Can anyone help me, please?




Aucun commentaire:

Enregistrer un commentaire