vendredi 26 juin 2015

prevent repetition of the numbers by not use of Collection Shuffle [Java]

I used random function in my code however i dont know how could i prevent repetition.Also i read another questions about this subject but i dont want to use "Shuffle".

I have different group of machines and i want to get randomly number of atn machine.

Random rand = new Random();
int range = 20;
for(int j = 1; j <= Const.GROUPA; j++)
{
    String group1 = String.valueOf(j);
    String atn = String.valueOf(rand.nextInt(range-1) + 1);  // +1 prevents the getting 0 value.
    String output1 = "ATN number " + atn + " from group number " + group1 +"A";
    System.out.println(output1);
}

Output :

ATN number 12 from group number 1A
ATN number 1 from group number 2A
ATN number 7 from group number 3A
ATN number 12 from group number 4A   // 2 times number 12!

Thanks for all help and clues.




Aucun commentaire:

Enregistrer un commentaire