Challenge: price brackets
Many real calculations work in brackets: one rule up to some amount, another rule above it. A long else if chain handles them well. Each branch covers one bracket, and because the chain stops at the first true condition, each branch can assume the earlier brackets didn't match.
int weight = 7;
int price;
if (weight <= 2) {
price = 5;
} else if (weight <= 10) {
price = 5 + (weight - 2) * 2;
} else {
price = 21 + (weight - 10);
}
System.out.println("Price: " + price);
Price: 15The price is set in every branch, so after the chain it always has a value. (int price; creates the variable without a value; Java checks that every path gives it one before it's used.)
The end of part 1
This step ends the material of the MOOC's first part. Its last section, Programming in our society, is a short read, with no exercises, about how much everyday life (communication, shopping, travel) runs on software, and how programmers are responsible for making it work well for everyone who uses it, including people who aren't used to computers.