81.3k views
2 votes
Create an application named ConvertMilesToKilometers whose Main() method prompts a user for a number of miles, passes the value to a method that converts the value to kilometers, and then returns the value to the Main() method where it is displayed. A mile is 1.60934 kilometers.

User MaurGi
by
6.4k points

1 Answer

5 votes

Answer:

The solution codes are written in Java as follows:

  1. import java.util.Scanner;
  2. public class ConvertMilesToKilometers {
  3. public static double convert_to_km(double miles)
  4. {
  5. double km = miles * 1.60934;
  6. return km;
  7. }
  8. public static void main(String[] args) {
  9. System.out.print("Enter miles: ");
  10. Scanner input = new Scanner(System.in);
  11. double inputMiles = input.nextDouble();
  12. System.out.println(inputMiles + " mile(s) = " + convert_to_km(inputMiles) + " km");
  13. }
  14. }

Step-by-step explanation:

Line 1 (Import Java Scanner Class)

  • Since the application is expected to get an input miles from user, the Java Scanner class is needed.
  • The Java Scanner class will be required to create a Scanner object to get input from user (Line 15).

Line 5 -10 (Create a method to convert mile to km)

  • This method accept one input (miles) and convert it to km.
  • km is returned as the output.

Line 14-16 (Get user input for miles )

  • A Scanner object is created in Line 15.
  • To get user input for miles, the nextDouble() method of the Scanner object is used (Line 16).
  • The nextDouble() is a method dedicated to get a decimal number as input (since miles is often in decimal format rather than an integer).

Line 18 (call method to convert miles to km and display the output)

  • Call convert_to_km() method by passing the user input miles (inputMiles) as argument.
  • The method will convert the miles to km and return output to the main method and display it in terminal using println() method.
User Zeyi Fan
by
6.3k points