Create a simple converter program that converts an entered distance from miles to kilometers and also from kilometers to miles.
New concepts: Input,
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 miles to kilometers, as well as from kilometers to miles. Print each conversion, clearly labeled, one per line.
Conversion: 1 mile = 1.609344 kilometers
Your final output should look something like this. Note how I executed the program three 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.
Please enter a distance to convert: 2.5
2.5 miles = 4.02336 kilometers
2.5 kilometers = 1.5534279805933349 miles
Please enter a distance to convert: 12
12.0 miles = 19.312128 kilometers
12.0 kilometers = 7.456454306848007 miles
Please enter a distance to convert: 1
1.0 miles = 1.609344 kilometers
1.0 kilometers = 0.621371192237334 miles
Your program will currently crash if you enter Strings instead of a number. At this point, that is okay; we'll soon learn how to prevent this.
What to Submit
UsernameA04.java file to Tamarin.
Grading [3 points]
- 1 - Compiles
- Your program compiles successfully (no errors)
- 0.6 - Input
- You prompt the user to enter a double, which you use to do the calculations.
- 1.4 - Output
- Program displays the correct results of the two conversions. Conversions are printed one per line, with one number followed by an
m and the other by a
k. (So you can either spell the words out or use the abbreviations mi and km.)
- Where's the demo code from class?
- Here: UserAge.java
- Is it okay if my answer is very very close to the correct answer but not exactly the same?
- Yes, that's fine. For example, you might get something like this (where km has a trailing 0000001):
Please enter a distance to convert: 50.2
50.2 miles = 80.78906880000001 kilometers
50.2 kilometers = 31.192833850314166 miles
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", miles)). Both are more complicated than we really want to deal with at this point of the class (but have a look into them if you're interested).