Re: Issue with array length in for loop
On 12/23/2010 10:46 PM, Steven Kennedy wrote:
I have a web application where I am extracting horse race information
from the internet. I have 3 main objects: "horse" which stores the
name and odds of the horse; "race" which has an array of horse objects
which are in the race; and "track" which has an array of race objects
which are run on the same day.
The part of the application which extracts the data from the internet
is working fine.
I am then trying to loop through each race on the track to determine
the most likely horse to win, but am having problems with the loop.
The array of races in the track seems to have length zero for a good
portion of the loop, then slowly increases to the correct length
My debugging code is basically
Track t = new Track(); //This initialises the race and horse arrays
for (Race r : track.getRaces()){
System.out.println("for race" + r.getRaceNumber() + " there is " +
r.getHorse().length + " horses");
}
The output is something like:
for race 1 there is 0 horses
for race 1 there is 0 horses
for race 1 there is 0 horses
for race 1 there is 0 horses
for race 1 there is 1 horses
for race 1 there is 1 horses
for race 1 there is 2 horses
for race 1 there is 2 horses
for race 1 there is 3 horses
...
for race 2 there is 0 horses
for race 2 there is 0 horses
...
...
for race 8 there is 15 horses
In my mind, this should just loop through the number of races and
display the number of horses in each race, but there is something
funny going on with the loop where the length of the horse array in
the race is zero for a lot of the loop, then starts to fill out, but
still the loop goes over the same race repeatedly before getting to
the end.
I have written this same application successfully in R and Objective-
C, but am stumped with this Java problem. Any thoughts as to the
source of the problem?
The source of the problem is in the source of the program, which you have not
revealed.
<http://sscce.org/>
I suspect that the part of the application that extracts the data from the
Internet is not working fine.
It looks like you have array fillers (and I wouldn't use arrays here, but
that's for a later conversation) running in a different thread or threads from
the array readers, and are encountering a race condition. (I can't help it;
that's what it's called.)
Also it looks like maybe you're putting a bunch of stuff in the constructor of
Track. Constructors are supposed to construct, period, not do all the method
work, too.
Black-box guessing like this runs the serious risk of being futile. I'll tell
you what. You go ahead and share an example that lets us duplicate your error
and then we'll see what we can do, ok?
--
Lew
Ceci n'est pas une pipe.