Practice: The Need for Methods
Extend a program that prints college football scores by copying and pasting its code, and see the problems copying causes.
Novice · C# · Updated
This program prints the points scored in each quarter, and the final score, of the top three college football teams in last week's games. (The scores are made up; change them if you like.)
| 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 |
Try it
In Git Bash, make a folder for this chapter and open a new file:
mkdir -p ~/bootcamp/methods
cd ~/bootcamp/methods
code scores.cs
Type in this program, save it, and run it with dotnet run scores.cs:
string teamName;
int rank, q1, q2, q3, q4, finalScore;
// Georgia
teamName = "Georgia";
rank = 1;
q1 = 12;
q2 = 14;
q3 = 6;
q4 = 7;
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();
// Alabama
teamName = "Alabama";
rank = 2;
q1 = 14;
q2 = 17;
q3 = 10;
q4 = 14;
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();
// Ohio State
teamName = "Ohio State";
rank = 3;
q1 = 21;
q2 = 10;
q3 = 14;
q4 = 7;
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
(2) Alabama
Q1: 14 Q2: 17 Q3: 10 Q4: 14
Final: 55
(3) Ohio State
Q1: 21 Q2: 10 Q3: 14 Q4: 7
Final: 52
int rank, q1, q2, q3, q4, finalScore; declares six int variables in one line. Each team's block then gives them new values.
Your task
Add Michigan and Clemson to the program by copying a team's block and changing its values. Don't try to write a method yet: do it the copy-and-paste way.
Run it again and check that all five teams are printed. Michigan's final score is 34, and Clemson's is 38.
Think about it
Before you read on, look at what you've built and answer these for yourself:
- How many times does the program now contain the four lines that print a team?
- Suppose the scoreboard should print
Final score:instead ofFinal:. How many lines would you change? What if you missed one? - What if you copied a block and forgot to change one of the quarter scores?
Every copy is another place for a mistake to hide. The next lesson shows how a method removes the copies.