A Problem Solved: Apples by the Box

In this lesson, we will write a Java program to compare the cost of buying apples individually and by the boxful.

Problem statement

You’re driving your car with your favourite person and spy a roadside stand. You stop and find a farmer who is selling apples individually and by the box. You buy a box of apples. How much would the apples have cost if you had bought the same number individually? How much did you save, if anything, by buying at the box rate?

Discussion

We really have two problems here, so let’s begin by answering the first question: How much would the apples have cost if you had bought them individually? Do we know enough to solve this first problem? No. We need to know:

  • The number of apples in a box
  • The price of one apple
  • The price of a box of apples

A Java program that solves this problem can begin by asking the user for this data. It then can make the necessary computations.

First question

Here is a rough outline of what needs to be done to answer the first question:

  • Get the data from the user.
  • Display the data.
  • Multiply the number of apples in a box by the price of one apple.
  • Display the result of the multiplication—the product—that is the cost of buying the same quantity of apples individually.

Second question

It turns out that we can answer the second question (How much did you save?) by adding the next two steps to our solution:

  • Subtract the price of a box of apples from the product.
  • Display the difference.

The steps that we have listed in our solution are collectively called an algorithm. You can write the steps in English—as we have done here—or in a combination of English and Java, as we will do in the future as you learn more Java. Such a combination of languages is called pseudocode.

The program

The following Java program solves this problem. We have combined the declarations of variables with their first assignments. Although you could declare all of the variables at the beginning of the method main and then assign values to them later, you generally should not do so.

Get hands-on with 1200+ tech skills courses.