Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Lucky Numbers Program with ArrayList -- Help!!

807589Dec 14 2008 — edited Dec 20 2008
Hi guys. I'm having quite a bit of trouble with this program I've been assigned to do...it's called LuckyNumbers. The instructions are a bit of complicated, but here's what I have to do:

Put the numbers from 1 to 250 in a list.
The first Lucky number is 1
Look for the next remaining number in the list---it's 2
Of the numbers that are left—cross out every 2nd number.
Look for the 2nd number left—it's the second Lucky number—it's 3
Of the numbers that are left—cross out every 3rd number
Look for the 3rd number left—it's the third Lucky number—it's 5
Of the numbers that are left—cross out every 5th number
and so on…………..

I have a write a method for this, and I've decided to use an ArrayList in my code so that I can remove and add elements with the list automatically shrinking and growing. I've written the method and I don't see why it shouldn't work, but an error keeps popping up with the IndexOutOfBounds message, which is annoying. I'll include my code here:
public static void lucky()
    {
        ArrayList<Integer> list = new ArrayList<Integer>();
        
        for (int count = 1; count <= 250; count++)
            list.add(count);

        int num;
        int a = 2;
        
        while (list.size() > 25)
        {
            for (num = a; num <= 250; num = num+a)    
                list.remove(num);
            a = list.get(num-1);   // decides what the next "cut-off" number will be
        } 
        
        int n = list.size();         // print the ArrayList
        for (int index = 0; index < n; index++)
        System.out.println(list.get(index));        
    }
So that's it. If anybody could help me figure out what to do, or just modify my code somewhat, I would be immensely grateful. I'm a bit of a novice at Java programming! Thanks in advance. ^_^
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 17 2009
Added on Dec 14 2008
2 comments
376 views