Practice: Creating Methods

Replace the football program's copied blocks with one method that takes each team's scores as parameters.

Apprentice · C# · Updated

In Practice: The Need for Methods you printed five teams by copying the same block five times. Now you'll make the code DRY: one method that prints any team, called once per team.

The method needs every value that changes from team to team: the rank, the name and the four quarter scores. Those become its parameters. Everything that stays the same, the printing and the final-score sum, goes in its body.

Write the method

Open scores.cs from the earlier practice, or start a new file, scores2.cs. Put this method at the bottom of the file:

void DisplayTeamScores(int rank, string teamName, int q1, int q2, int q3, int q4)
{
    int finalScore = q1 + q2 + q3 + q4;

    Console.WriteLine("(" + rank + ") " + teamName);
    Console.WriteLine("Q1: " + q1 + "  Q2: " + q2 + "  Q3: " + q3 + "  Q4: " + q4);
    Console.WriteLine("Final: " + finalScore);
    Console.WriteLine();
}

The variable declarations from the old program have moved into the parentheses. Anyone who calls this method must give it a value for each one. Notice that the method knows nothing about Georgia or Alabama: it only knows how to print the values it's given.

Run the file now, with the old team blocks deleted and no calls yet. It prints nothing. Writing a method doesn't run it; only a call does.

Call it

Above the method, call it once for Georgia:

// The arguments go in the parameters' order: rank, teamName, q1, q2, q3, q4
DisplayTeamScores(1, "Georgia", 12, 14, 6, 7);

void DisplayTeamScores(int rank, string teamName, int q1, int q2, int q3, int q4)
{
    int finalScore = q1 + q2 + q3 + q4;

    Console.WriteLine("(" + rank + ") " + teamName);
    Console.WriteLine("Q1: " + q1 + "  Q2: " + q2 + "  Q3: " + q3 + "  Q4: " + q4);
    Console.WriteLine("Final: " + finalScore);
    Console.WriteLine();
}
(1) Georgia
Q1: 12  Q2: 14  Q3: 6  Q4: 7
Final: 39

Your task

Add a call for each of the other four teams, so the program prints all five:

Rank Team Q1 Q2 Q3 Q4
1 Georgia 12 14 6 7
2 Alabama 14 17 10 14
3 Ohio State 21 10 14 7
4 Michigan 10 7 0 17
5 Clemson 14 6 8 10

When you're done, the top of your file is five short lines, one per team. Check the final scores: 39, 55, 52, 34 and 38.

Then try this

  • Change Final: to Final score:. How many lines did you change this time?
  • Call the method with the arguments in the wrong order, such as DisplayTeamScores("Georgia", 1, 12, 14, 6, 7);. Read the error: the types don't match, so C# won't build it. Parameters protect you from some mistakes.
  • Swap two quarter scores in a call. This time C# can't help: both are int. Order matters, so read your calls carefully.

So what

Five copies became one method and five calls. A fix now happens in one place, and a new team costs one line.

Key terms

Cheat sheets

Related