Java Arena
Step 2 of 4

Names and comments

When you read your own code, you tend to see what you meant to write, not what's actually there. That's why a bug can sit in plain sight while you read over it again and again.

Two habits make code easier to read, both for others and for you next week.

Names that say what a value is

Compare these two versions of the same calculation:

int a = 3;
int b = 250;
int c = a * b;
System.out.println(c);
Output
750
int tickets = 3;
int priceInCents = 250;
int totalInCents = tickets * priceInCents;
System.out.println(totalInCents);
Output
750

Both work, but only the second one tells you what it does. A wrong line such as int totalInCents = tickets + priceInCents; stands out when the names make sense, and hides easily among a, b and c. Short names are fine where the meaning is obvious, such as i for a loop counter.

Comments that explain why

You met comments in module 1: // runs to the end of the line, and /* runs until */. Java skips them, so they're written for people:

/* Prices are kept in cents,
   so no rounding happens. */
int priceInCents = 250;
// A discount of 10 percent on orders of 4 or more
int tickets = 4;
if (tickets >= 4) {
    priceInCents = priceInCents * 90 / 100;
}
System.out.println(tickets * priceInCents);
Output
900

Good comments say what the code can't: why it's written this way, or what a rule means. A comment that repeats the code (// adds one to count above count++;) adds nothing, and a comment that no longer matches the code is worse than none.

A comment that states a rule is also a debugging aid: when the code and the comment above it disagree, one of them is wrong, and you've found where to look.

Your task

Challenge 1 of 3

In this ticket program, one line doesn't do what the comment above it says. Find it and fix the code (the comments are right). With the input 5 it prints:

Total: 5200 cents

Challenge 2

This program works, but its names hide what it does. It reads a distance in kilometers and a time in minutes, and prints the average speed in kilometers per hour. Rename the variables a, b and c to names that say what they hold (the output must stay the same). With the input 42 and 210 it prints:

Average speed: 12.0 km/h

Challenge 3

What does this program print? Watch for the comments.