Answer to Exercise 10

This exercise is quite tough, and should have produced a lot of code. In fact, so much code that we've split the answers over three pages, one for each programming course. You can click a link below to go straight to the answer. But have a look at our analysis first, as it might give you some insights. You can then try again before peaking at the answer.

So you had this string to parse first:

string results = "Manchester United 1 Chelsea 0, Arsenal 1 Manchester United 1, Manchester United 3 Fulham 1, Liverpool 2 Manchester United 1, Swansea 2 Manchester United 4";

You can use Split on this to create an array. The first position in the array would then look like this:

results[0] = "Manchester United 1 Chelsea 0";

Each match can then be handed to a method for further parsing.

In this method, you can split the match into an array. The array would then look like this:

match[0] = "Manchester";
match[1] = "United ";
match[2] = "1";
match[3] = "Chelsea";
match[4] = "0";

When Manchester United are playing at home, their score is at position 2 in the array. When they are playing away, it will be at the final position of the array. (This might not be position 4. They might be playing Swansea City, in which case the away score would be at position 5 in the array.)

So you need a way to check if they are playing at home or away. You can do this with an indexOf or InStr method. This will tell you if the string "Manchester United" is in the result "Manchester United 1 Chelsea 0." If you get an answer of 0 then you know Manchester United is at the start of the string, and therefore playing at home. If it's greater than 0 then you know they are playing away from home. (You need to use Trim on your string to get rid of any white space).

So if Manchester United are playing at home you can check match[2] against the final position in the array;

If first_score > second_score Then

'HOME WIN + "-" first_score + "-" + second_score

End If

We have set up our method to return a value in the format:

"POINTS_SCORED-GOALS_FOR-GOALS-AGAINST"

In the first match, this would produce the following:

"3-1-0"

This means, 3 points gained, 1 goal scored, and 0 conceded.

When we get this string back from the method we can than parse the three parts.

Anyway, here are our three answers (there could well be an easier way to do things, though, and we're definitely not saying ours is the best):

VB NET Answer

C# NET Answer

Java Answer