Saad Saad - 2 months ago 9
Java Question

Java for loop help needed

So i am doing this question where i have to create ten new objects and put them randomly into a an Event class. What i want is this:

Events:
2: 4:00 PM: Event #8 (priority 3)
11: 2:00 PM: Event #10 (priority 1)
12: 5:00 PM: Event #7 (priority 3)
14: 10:00 PM: Event #2 (priority 1)
15: 6:00 PM: Event #6 (priority 3)
16: 7:00 PM: Event #5 (priority 2)
19: 3:00 PM: Event #9 (priority 2)
25: 9:00 PM: Event #3 (priority 1)
26: 11:00 PM: Event #1 (priority 3)
28: 8:00 PM: Event #4 (priority 1)


I have this little code here which is supposed to create TEN new objects, however i am not getting TEN, instead sometimes i get 6, sometimes 7 etc.

String[] tenEvents = {"Event #1", "11:00 PM", "Event #2", "10:00 PM", "Event #3", "9:00 PM",
"Event #4", "8:00 PM", "Event #5", "7:00 PM", "Event #6", "6:00 PM", "Event #7", "5:00 PM",
"Event #8", "4:00 PM","Event #9", "3:00 PM", "Event #10", "2:00 PM"};

for (int i = 0; i < tenEvents.length; i+=2){
rand = (int) (Math.random() * (month.length));
if (month[rand] != null) {
rand = (int) (Math.random()*(month.length));
} else {
priority = (int) (Math.random() * 3) + 1;
month[rand] = new Event(tenEvents[i], tenEvents[i+1], priority);
}


My output is this:

Events:
11: 10:00 PM: Event #2 (priority 3)
14: 9:00 PM: Event #3 (priority 2)
18: 7:00 PM: Event #5 (priority 1)
19: 6:00 PM: Event #6 (priority 1)
24: 11:00 PM: Event #1 (priority 3)
29: 8:00 PM: Event #4 (priority 3)


AND this:

Events:
3: 11:00 PM: Event #1 (priority 1)
7: 9:00 PM: Event #3 (priority 3)
10: 8:00 PM: Event #4 (priority 2)
12: 10:00 PM: Event #2 (priority 3)
14: 7:00 PM: Event #5 (priority 3)
26: 6:00 PM: Event #6 (priority 3)
28: 5:00 PM: Event #7 (priority 2)


I can't seem to get ten events. I was trying to do it with while loop but i have no idea where i am going with that. Can anyone point me in the right direction please?

Answer

Why not make an array of Events like this?

Event[] tenEvents = 
{new Event("Event #1", "11:00PM", priority = (int) (Math.random() * 3) + 1),...,
new Event("Event #10", "2:00PM", priority = (int) (Math.random() * 3) + 1)};

This way all of your Event objects are made with random priorities but allow you to pass in your parameters still. Then go through your month array and randomly assign. The randomizing loop could look something like this

for(int i = 0; i < tenEvents.length; i++){
   int rand = (int) (Math.random() * (month.length));
   while(month[rand] != null){
   rand = (int) (Math.random() * (month.length));
   }
   month[rand] = tenEvents[i];
}