vendredi 24 avril 2015

Generate number and check it is already in ArrayLis in JAVA

I would like to generate 10 random numbers. But before I add number into ArrayList, I need to check if my arraylist already contains number which is in range on "randomNumber - 50 > arrayListNumber and arrayListNumber < randomNumber + 50"

For example random number is 120 120-50=70 120+50=170 if randomNumber is 70...170, I will not add it to my arrayList and run again the cycle...

What is wrong in my code? package ee.tlu; import java.util.ArrayList; import java.util.List; import java.util.Random;

public class Testing {
    public Testing() {
        List < Integer > numbers = new ArrayList < > ();
        Random rand = new Random();
        int number = rand.nextInt(5000);
        int n = 0;
        boolean listis = false;
        numbers.add(number);
        while (n < 10) {
            number = rand.nextInt(5000);
            for (int k = number - 50; k < number + 50; k++) {
                if (numbers.contains(k)) {
                    listis = true;
                    break;
                }
            }
            if (!listis) {
                numbers.add(number);
                n += 1;
            }
        }
        System.out.println(numbers);
    }
    public static void main(String[] args) {
        new Testing();
    }
}




Aucun commentaire:

Enregistrer un commentaire