Convert miles to km
In this article, we will take a look at miles to km conversion with java program that takes number of miles to be converted as user input.
The relation between miles and km is
1 mile = 1.60934 km
which means that there are 1.60934 km in a mile.
So, to convert miles to km , we need to multiply the number of miles to be converted to kilometers by 1.60934.
Java program
Below is a java program that reads the number of miles to convert to kilometers as user input using scanner class.
Then, it multiplies this value by 1.60934.
Finally, it formats the result to 4 decimal places.
Scanner scanner = new Scanner(System.in); System.out.println("Enter distance in miles"); // read miles input String mileDist = scanner.nextLine(); // convert miles to km double kmDist = Double.parseDouble(mileDist) * 1.60934; NumberFormat format = new DecimalFormat("#.####"); System.out.println(mileDist + " miles to km is " + format.format(kmDist)); scanner.close();
Output is
Enter distance in miles
5
5 miles to km is 8.0467
Above program converts 5 miles to km.
Note that nextLine()
reads user input as a string. So, we need to convert it to a double
value using Double.parseDouble()
.
We can also use nextDouble()
method of scanner to directly read a double
value as shown below
Scanner scanner = new Scanner(System.in); System.out.println("Enter distance in miles"); // read miles input double mileDist = scanner.nextDouble(); // convert miles to km double kmDist = mileDist * 1.60934; NumberFormat format = new DecimalFormat("#.####"); System.out.println(mileDist + " miles to km is " + format.format(kmDist)); scanner.close();
Output is
10
10.0 miles to km is 16.0934
It successfully converts 10 miles to km.