Java: Sort lottery numbers in array
This class generates lottery numbers and reads them into an array.
The values contained in the array are then sorted in ascending order.
In the meantime, I’ve been raging like a lunatic on the living room table 🙂 I followed the wrong approach for 4 hours and then moved on to first reading in, then sorting out. Now it works.
[code]public class LotterynumberenArraySortierung { public static void main(String[] args) { // TODO Auto-generated method stub boolean[] drawnball; int[] lotterynumbers; int randomnumber; int swap; lotterynumbers= new int[6]; drawnball= new boolean[49]; //Assignment of values to the array for ( int i =0; i < lotterynumbers.length; i ++){ if (i==0){ randomnumber=(int) (Math.random()*49+1); lotterynumbers[0]=randomnumber; drawnball[randomnumber-1]=true; } randomnumber=(int) (Math.random()*49+1); while (drawnball[randomnumber-1]==true){ randomnumber=(int) (Math.random()*49+1); } drawnball[randomnumber-1]=true; lotterynumbers[i] = randomnumber; } //Sort the values within the array using a bubble sort-like method for (int i=0; i < lotterynumbers.length-1; i=i+1) for (int c=lotterynumbers.length-1; c > i; c=c-1) if (lotterynumbers[c-1] > lotterynumbers[c]) { //The number to be swapped is temporarily stored under the variable swap to free its space. swap = lotterynumbers[c-1]; //Old number is exchanged for new one lotterynumbers[c-1] = lotterynumbers[c]; //swap is used at the rear lotterynumbers[c] = swap; } // Output of contents for ( int i =0; i <= 5; i ++){ System.out.println("Lotterynumber " + (i+1) + " ist: " + lotterynumbers[i]); } } } [/code]