Create a simple converter program that converts an entered distance from feet to meters and also from meters to feet.
Textbook: 2.6; 10.1 - 10.3
New concepts: Input,
Scanner; exception handling.
Ask the user to enter a distance. Read this in as a decimal number (
double) using a Scanner. Then print what that distance would be if converted from feet to meters, as well as from meters to feet. Print each conversion, clearly labeled, one per line.
Conversion: 1 foot = 0.3048 meters
If the user enters something that is not a number, your program must catch the resulting
InputMismatchException so that it does not crash. Instead, it should print a polite error message and then end (without printing any other output).
Therefore, your final output should look something like this. Note how I executed the program four separate times; the command prompts and java command are not part of the output of the program. The stuff in green here is the input I typed when prompted by the program.
sp10code mmenor$ java MmenorA04 Please enter a distance to convert: 2.5 2.5 feet = 0.762 meters 2.5 meters = 8.202099737532809 feet sp10code mmenor$ java MmenorA04 Please enter a distance to convert: 12 12.0 feet = 3.6576000000000004 meters 12.0 meters = 39.37007874015748 feet sp10code mmenor$ java MmenorA04 Please enter a distance to convert: 1 1.0 feet = 0.3048 meters 1.0 meters = 3.280839895013123 feet sp10code mmenor$ java MmenorA04 Please enter a distance to convert: one hundred You must enter a number (only). Please try again.
UsernameA04.java file to Tamarin.
fand the other by a
m. (So you can either spell the words out or use the abbreviations ft and m.)
Please enter a distance to convert: 100 or so meters 100.0 feet = 30.48 meters 100.0 meters = 328.0839895013123 feet
Please enter a distance to convert: 3048 3048.0 feet = 929.0304000000001 meters 3048.0 meters = 10000.0 feet
The reason for this is how
doubles are stored internally. They are only precise to a certain number of decimal places and, depending on which math operations you perform on them and in which order, that last decimal place may get rounded a digit or two either way along the way. This is always a danger with
double math that will become more obvious when we get to to the
== (equality) operator next week.
There is a way to format floating point numbers when you print them, so you don't always have to have a big ugly string of digits. However, the formatting either involves the use of an object (such as an instance of
java.text.DecimalFormat), or else a rather arcane formatting code (for example:
System.out.printf("%.2f\n", feet)). Have a look at the textbook (section 3.6) if you're interested in these.