Practice: Creating Functions
Replace the copied team-score code with one displayTeamScores function that takes each team's rank, name and scores as parameters.
Apprentice · Java · Updated
In Practice: The need for functions, you copied the same lines for every team. Now you'll remove that repeated code.
We will now make our code more DRY by creating a function to display team information. This makes our code easier to manage.
The function in this lesson is a bit more complex than the examples in Organizing code into functions. The function needs all of the statistical data about each team to display the correct information. This is done by adding parameters.
We will replace the repeated lines of code with our new function. The function does NOT include the specific text and numbers for any of the teams. Instead, we will create parameters (variables) that will allow us to pass in the values for each team when we call the function.
Instructions
Look over the function definition below. Add a class named Functions02 with an empty main method, paste this function into the class below main, and run it.
Notice that when you execute this code, that there is no output to the screen. This is because this code only creates the function. The function is not yet being called, and therefore is never executed.
// Notice that the variable declarations have been moved into
// parentheses - these are called input parameters.
// Anyone who wants to execute this function MUST provide
// values for all of these parameters.
public static void displayTeamScores(int rank,
String teamName,
int q1, int q2, int q3, int q4)
{
int finalScore = q1 + q2 + q3 + q4;
System.out.printf("(%d) %s \n", rank, teamName);
System.out.println("-------------------------------");
System.out.println(" Q1 Q2 Q3 Q4 Final");
System.out.println(" --- --- --- --- -----");
System.out.printf(" %-2d %-2d %-2d %-2d %d \n",q1, q2,q3,q4
,finalScore);
System.out.println();
}
Notice that this function does not have any information about the specific teams. The only thing that you focus on in your code in this function is the logic to calculate and display the information that you have been given.
Executing a Function
Now that the function has been created, you must execute the function to display the stats.
// the parameter order MUST BE rank, teamName, q1, q2, q3, q4
displayTeamScores(1, "Georgia", 12, 14, 6, 7);
Add code to display the scores of all of the top 5 teams.
| 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 |
public static void main(String[] args)
{
// add your code here
displayTeamScores(1, "Georgia", 12, 14, 6, 7);
displayTeamScores(2, "Alabama", 14, 17, 10, 14);
// add the remaining teams
}