slanted W3C logo

Lab 02—eCheck02B Tutorial

eCheck02B can be found on page 97 of the textbook .

The Problem

Write a Java program that starts with 2 positive integers and:

  1. computes their product
  2. computes the product rounded up to the nearest multiple of 5; the product:
    • 4 should be rounded up to 5
    • 5 should remain 5
    • 6 should be rounded up to 10
  3. computes the average of the product and the rounded product
    • if the product is 4, the desired average is the average of 4 and 5
    • if the product is 5, the desired average is the average of 5 and 5
    • if the product is 6, the desired average is the average of 6 and 10

Step 1: Create The Class

Step 2: Create The Variables

Step 3: Compute The Product

What would happen if the variables first and second had been declared as type int?

What would happen if the variables first and second had been declared as type double?

Step 4: How to Round Up?

The textbook provides a hint: You can round down to the nearest multiple of 5 by dividing the integer by 5 and then multiplying the result by 5.

4 / 5 * 5
⇒ (4 / 5) * 5
⇒ 0 * 5
⇒ 0

5 / 5 * 5
⇒ (5 / 5) * 5
⇒ 1 * 5
⇒ 5

6 / 5 * 5
⇒ (6 / 5) * 5
⇒ 1 * 5
⇒ 5

How much do you have to add to 6 to get the rounded result of 10?

Step 4: How to Round Up?

(6 + 4) / 5 * 5
⇒ 10 / 5 * 5
⇒ (10 / 5) * 5
⇒ 2 * 5
⇒ 10

(7 + 4) / 5 * 5
⇒ 11 / 5 * 5
⇒ (11 / 5) * 5
⇒ 2 * 5
⇒ 10

(8 + 4) / 5 * 5
⇒ 12 / 5 * 5
⇒ (12 / 5) * 5
⇒ 2 * 5
⇒ 10

(9 + 4) / 5 * 5
⇒ 13 / 5 * 5
⇒ (13 / 5) * 5
⇒ 2 * 5
⇒ 10

(10 + 4) / 5 * 5
⇒ 14 / 5 * 5
⇒ (14 / 5) * 5
⇒ 2 * 5
⇒ 10

Step 5: Round the Product

Step 6: Compute the Average

Which of the following statements correctly computes the average?

double average = (1 / 2) * (product + roundedProduct);

double average = product + roundedProduct / 2;

double average = (product + roundedProduct) / 2;

double average = (double) (product + roundedProduct) / 2;

double average = (product + roundedProduct) / (double) 2;

double average = (product + roundedProduct) / 2.0;

double average = 0.5 * (product + roundedProduct);

Step 6: Compute the Average