Array sort by Ascending in for loop
I got trouble wh开发者_StackOverflow中文版en i try to sort array in for loop.
I give you my code follow:
public class Lottery {
public Lottery() {
java.util.Random iRandom = new java.util.Random();
int num[] = new int[6];
java.util.Arrays.sort(num);
for(int i =0 ; i < num.length; i++) {
java.util.Arrays.sort(num);
num[i] = iRandom.nextInt(49)+1;
System.out.println(num[i]);
}
}
public static void main(String[] args) {
Lottery lott = new Lottery();
}
}
In my above code, i can print random number for using "For Loop" but i try to sort it by ascending but it doesnt work.....
The way i do is right?
Could everybody can help me?
Thank you!
Best Regards!
Put the Arrays.sort(num)
call AFTER you're finished generating the random numbers.
public Lottery(){
java.util.Random iRandom = new java.util.Random();
int num[] = new int[6];
for(int i =0 ; i < num.length; i++)
num[i] = iRandom.nextInt(49)+1;
Arrays.sort(num);
}
You're sorting the array as you go through it and inserting data into the array.
What you should be doing is:
public Lottery() {
java.util.Random iRandom = new java.util.Random();
int num[] = new int[6];
//java.util.Arrays.sort(num);
for(int i =0 ; i < num.length; i++) {
num[i] = iRandom.nextInt(49)+1;
}
java.util.Arrays.sort(num);
for(int i : num) {
System.out.println(i);
}
}
You're changing the array after you sort it, which breaks the sort order.
What you can do to sort in acceding order is:
java.util.Arrays.sort(array);
edit: Also as said in the comments: Get the random numbers you want. Then sort in revese. (to much sorting can make the program slow)
精彩评论