Java Arena
Step 6 of 6

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);
Output
Price: 15

The 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.

Your task

Challenge 1 of 3

Shipping is free for orders of 50 euros or more; smaller orders pay 5 euros. Read the order total (whole euros) and print the shipping cost. For the input 30 the program prints:

Shipping: 5 euros

For 50 or more it prints Shipping: free.

Challenge 2

A delivery service charges by distance (an invented price list):

Distance Price
up to 5 km 3.0 euros
over 5 km, up to 20 km 3.0 plus 0.5 for every km over 5
over 20 km 10.5 plus 1.0 for every km over 20

Read the distance in whole kilometres and print the price. For the input 12 the program prints:

Price: 6.5 euros

Challenge 3

A library's late fee (an invented table), for a book returned some whole number of days late:

Days late Fee
0 nothing
1 to 7 1 euro per day
8 to 14 7 euros plus 2 per day over 7
15 to 30 21 euros plus 3 per day over 14
over 30 70 euros

Read the number of days and print Nothing to pay or Fee: N euros. For the input 10 the program prints:

Fee: 13 euros