Back to Challenge Set 15

Debug Challenge: Methods

Difficulty  

divider

Objective

Four short programs about writing and calling methods — Activities 2.1 to 2.3.

One will not build. Two run and give a wrong answer with no warning at all. And one works for the first call and crashes on the second.

Part of each answer is saying which kind of failure it is— because the kind tells you where to look.


The Four Programs


Bug 1

This should print the doubled value, 16. It does not build.

Bug 1
Console.WriteLine(Double(8));
int Double(int n)
{
n * 2;
}

Also: it gives two errors, on two different lines. Say what each one is objecting to.


Bug 2

This should print a crew line for each person. The first line is right; the second is nonsense.

Bug 2
CrewLine("Avery", "Pilot");
CrewLine("Engineer", "Blake");
void CrewLine(string name, string role)
{
Console.WriteLine($"{name} - {role}");
}

Also: C# gave no error. Say what would have to be different about CrewLine's parameters for C# to catch this mistake.


Bug 3

This should show the price with 8% tax added. Instead, this is what it prints:

Bug 3
double price = 20;
AddTax(price);
Console.WriteLine($"With tax: {price:F2}");
double AddTax(double price)
{
return price * 1.08;
}
Output
With tax: 20.00

Also: AddTax itself is correct. Say where the taxed price went.


Bug 4

This should print an average for each room, then finish the report. Room 101 prints. Then it crashes.

Bug 4
Console.WriteLine($"Room 101: {Average(340, 4)}");
Console.WriteLine($"Room 102: {Average(0, 0)}");
Console.WriteLine("Report finished.");
int Average(int total, int count)
{
return total / count;
}

Also: the crash happens on line 7, but the bad value came from somewhere else. Say which line, and change Average so that an empty room returns 0 instead of crashing.


Submit

For each program, give:

  • Which kind of failure it is — will not build, crashes, or runs and is wrong
  • One sentence on what was wrong
  • The corrected line, or lines, of code

Plus the four written answers.

Work them out by reading first. Running the code tells you that something is wrong; it rarely tells you why, and on the exam there is no computer.

Commence Debugging