Create a directory for this exercise. In that directory, create a file named
Weight.java
. In this file, create a class named Weight
, containing
a program that converts a weight in kilograms into the equivalent weight in
old-fashioned Imperial units of pounds and ounces.
Your program should allow the weight in kilograms to be input by the user as
a floating-point value, and it should represent this value internally using
the double
type. It should convert this value into numbers of pounds
and ounces, using an int
variable to represent the number of pounds and a
double
variable to represent the number of ounces. The program should
display the converted weight in a single line of output. The number of
ounces should be displayed with 1 decimal place of accuracy.
Here is an example of what the user should see when running the program from a terminal window:
$ java Weight
Enter weight in kilograms: 1.8
Equivalent imperial weight is 3 lb 15.5 oz
Note that the output uses the standard abbreviations for pounds and ounces: ’lb’ and ‘oz’.
Use the Scanner
class to handle input of the weight in kg – see
Section 2.4.6 of Eck’s book or the API documentation for
examples.
Use a single call to System.out.printf()
to output the result. Remember
that this works in a similar way to C’s printf()
function.
Follow a two-step approach, in which the weight is converted first into
a total number of ounces. You can easily google the required conversion
formula for this. The second step is to break down the total number
of ounces into a whole number of pounds and the remaining number of ounces,
noting that there are 16 ounces in a pound. You’ll find the %
operator
useful here.
□