2

I got trouble when 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!

2
  • 1
    you should probably generate all of the random numbers you want then call Arrays.sort(...) Commented Jul 20, 2011 at 18:25
  • You also need to check for duplicate random numbers. A lottery usually has unique random numbers. Commented Jul 20, 2011 at 18:47

4 Answers 4

11

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

First of all Thank you so much I try to do follow u but when i print it , it show result such as: > 0 0 0 13 14 15 but i need range from 1-49 i dont know what problem occur Thank you !!
How are you printing it? There's no way to get num[i]==0 since iRandom.nextInt(49)+1 will always return an int between 1 and 49
It's mean can not to print from 1-49? when num[i]=0?
Try printing the array using System.out.println(Arrays.toString(num));.
3

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);
    }
}

Comments

3

You're changing the array after you sort it, which breaks the sort order.

Comments

0

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)

1 Comment

he's asking about sorting in ascending order, wouldn't reverse order sort in descending?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.