Feet to Meters Lab
The purpose of this lab is to gain familiarity with basic Java programming, to learn how to read input from the keyboard, and how to format output (which will involve the use of objects).
Write an application that converts a person's height in feet and inches to meters.
Run at least two test cases. How many meters tall are you? How many meters tall am I (I am 6 feet tall)? Be sure to check your results.
Your program may make use of the Scanner class to read input from the user.
When you print the results, it may look something like this:
How tall are you in integral feet?
6
How many additional inches?
1
You are 1.8541999999999998 meters tall
The above output has more decimal places than we need. Use a class from the Java Runtime Library called NumberFormat to control the number of decimal places. (Look it up in the API.)
- Import the package which contains the class:
import java.text.*;
- Invoke a static method of the class to get an object of the class
NumberFormat fmt = NumberFormat.getInstance();
- Invoke an instance method on the object to customize it to the desired number of decimal places
fmt.setMaximumFractionDigits (2);
- Invoke an instance method on the customized object to format the number into a suitable string:
String metersStr = fmt.format (meters);
- Print the string.
Our output is now more readable:
You are 1.85 meters tall
Have Fun!
|