Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with a Java programming assignment
#1
[COLOR="Red"]Hi guys, I'm having troubles.

http://pastie.org/728471

That is the code.

array1 is a template class with 30 people in it.
array is a template class with 8 vehicles in it.

What I want accomplished is that 8 random people's ids (an attribute of the People template class) are given a car.

What i have correct is that there are always 8 random people's id's chosen. The countV is also increased to 8.

What I'm having troubles with is always displaying 8 winners. More often than not, only 7 winners' names are shown. Sometimes 8, sometimes 6, once or twice 5.

Now, what is going wrong, and how can i always make 8 people's first names show up?

[/COLOR]
Reply
#2
The problem is that your algorithm just chooses 8 random numbers - it doesn't care whether there are repeats. When only 7 winners are displayed, that is because it chose one of them twice.

If you're allowed to rearrange the array, I think you can shuffle it (or partially shuffle it) and then print the first 8 as winners and the rest losers. If not, or if the IDs don't work the way I assume they do, you'll have to find some way of "re-rolling" IDs if they are already taken.
Reply
#3
If someone wins multiple vehicles they're not printed multiple times.
Reply
#4
Never mind.

Easiest solution would be to allocate another array of 8 random non-repeating numbers for your lottery.

Code:
int countV=0;
    while (countV<8)
    {
        int num=(int)(1+Math.random()*(30));        
        for (int i=0;i<=array1.length-1 ;i++ )
        {
            if (num == array1[i].getLotID() && array1[i].getFlag())
                countV--;
            else if (num == array1[i].getLotID())
            {                
                
                //System.out.println("TEST");
                //System.out.println(array1[i].toStringP());
                array1[i].setVehicleProject(array[countV]);        
                array1[i].setFlag(true);
            }
        }
        countV++;        
    }
    for (int i=0;i<=array1.length-1 ;i++ )
    {
        if (array1[i].getFlag())
        {
            System.out.println(array1[i].getFirstName()+" is a Winner");
        }
        else
        {
            System.out.println(array1[i].getFirstName()+" is a Loser");
        }
    }

This should work too, though I'm not 100% sure about the implementation of your code.
Reply
#5
[COLOR="Red"]I see. well, to be honest, later in the project i need to choose a different ID if a person was already chosen...

But i'll try what you guys stated here.[/COLOR]
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)