Generating non-duplicate numbers using Arrays, not ArrayList<> in Java -


i'm doing old lotto exercise , need use array[] of integers , not arraylist. have thought work, seem wrong. looked posts similar these , of them involved arraylist<>. here partition of code.

integer[] lottonums; lottonums = new integer[7];  for(int = 0; < lottonums.length; i++){      lottonums[i] = randomnums.nextint((59)+1);       if(i <= 5) {         if(lottonums[i].equals(lottonums[i+1])){             if(lottonums[i] < 58 && lottonums[i] > 1)                 lottonums[i] = lottonums[i] +1;         }     }     else if(i >= 1) {         if(lottonums[i].equals(lottonums[i-1])){             if(lottonums[i] < 58 && lottonums[i] > 1)                 lottonums[i] = lottonums[i] +1;         }     } }  arrays.sort(lottonums); system.out.print("winning numbers: "+lottonums[0]); (int = 1; < 6; i++) {       system.out.print(", " + lottonums[i]); } system.out.print(system.getproperty("line.separator")); system.out.println("bonus number: "+lottonums[6]); 

i need generate number in between 1 , 59 , not duplicate. trying pair value stored in element before , after (if had one) , if equal it, add 1 it. run few times , every once in while im still getting duplicate numbers. how can efficiently, using arrays[] of integers only?

edit:

initialized array remove nullpointerexception.

updated code:



for(int = 0; < lottonums.length; i++){          lottonums[i] = randomnums.nextint((59)+1);      } (int = 0; < 6; i++) {            int rnd = randomnums.nextint((lottonums).length-i);            int k = lottonums[lottonums.length-i-1];            lottonums[lottonums.length-i-1] = lottonums[rnd];            lottonums[rnd] = k;         }      arrays.sort(lottonums);     system.out.print("winning numbers: "+lottonums[0]);     //printing lotto numbers     (int = 1; < 6; i++) {           system.out.print(", " + lottonums[i]);     }         system.out.print(system.getproperty("line.separator"));         system.out.println("bonus number: "+lottonums[6]); 

you can switching selected number last number in array each time, , selecting next prefix have not yet stored:

for (int = 0; < 6; i++) {    int rnd = randomnums.nextint(numbers.length-i);    int k = numbers[numbers.length-i-1];    numbers[numbers.length-i-1] = numbers[rnd];    numbers[rnd] = k; } 

at end of loop selected numbers in numbers[numbers.length-7..numbers.length-1], etc.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -