The most important clue you're missing is that in your final for loop, you will want to
test whether you have already seen the car and add the distance to the existing value if you have:
As Julian already indicated, you can iterate over all the entries in the map using an iterator. You could print the results using
This will print the total for each, and the total for all drivers.
I realise that you're only just starting on your Java journey, so what follows may be overkill. Just check out what is meaningful to you and ignore what isn't (yet).[list]You are declaring all your variables
way too early, give them a scope that is far too large, and you also initialise them where you don't need to. Instead of
You could write
Because you never intend to use the variables without first assigning to them (the same can be said about your Car class). This way, you make that very clear, and as an added bonus the compiler will warn you if under any circumstances you might use the variables without assigning first. But even better would be:
This reduces the scope of the variables to the absolute minimum necessary. Reducing the scope makes the code much easier to read and maintain, because you're explicit about where you will be using these variables and where you won't.
Along similar lines, the declaration of the "tm" variable should be moved to right before the for loop.[list]Staying on the subject of scope, turning your first while loop into a for loop allows you to restrict the scope of "line" to the loop:
Not everyone will like this idiom, though.[/list]
Using a fixed-length array for your cars means that you're building arbitrary limitations in your application (100 cars in this case). A List, for example an ArrayList, is usually a better idea.The fields in your Car class don't want to be initialised, as mentioned above. They also should be private. Finally, seeing that you are assigning them in the constructor and never changing them, you can just as well make that explicit by making them final. That way, everyone can immediately see that the Car class is immutable.In JDK 1.4, use of String.split is encouraged over using the legacy StringTokenizer class. In this case, it does make things a little simpler.Your run() method does three different things: capture the list of cars, sum the distances traveled, and print the results. Correspondingly, these operations should be implemented in three different methods.With these modificatons, the code starts to look like this:
There's more that could be said, but I'm afraid I've gone on for long enough now
Hope this helps,
- Peter
[ September 01, 2004: Message edited by: Peter den Haan ]