32.3k views
2 votes
3. Write a Java program that asks the user to enter a distance in meters. The program will then present the following menu of selections:

a. Convert to kilometers
b. Convert to inches
c. Convert to feet
d. Quit the program

The program will convert the distance to kilometers (=meters*0.001), inches (=meters*39.37) or feet (=meters*3.281), depending on the user’s selection. Each conversion should be handled by a separate method that takes the distance in meters as an argument

1 Answer

0 votes

Answer:

import java.util.Scanner;

public class DistanceConverter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

double distanceInMeters;

System.out.print("Enter distance in meters: ");

distanceInMeters = scanner.nextDouble();

char choice;

do {

displayMenu();

System.out.print("Enter your choice (a/b/c/d): ");

choice = scanner.next().charAt(0);

switch (choice) {

case 'a':

convertToKilometers(distanceInMeters);

break;

case 'b':

convertToInches(distanceInMeters);

break;

case 'c':

convertToFeet(distanceInMeters);

break;

case 'd':

System.out.println("Exiting the program...");

break;

default:

System.out.println("Invalid choice. Please try again.");

}

} while (choice != 'd');

scanner.close();

}

public static void displayMenu() {

System.out.println("Menu of selections:");

System.out.println("a. Convert to kilometers");

System.out.println("b. Convert to inches");

System.out.println("c. Convert to feet");

System.out.println("d. Quit the program");

}

public static void convertToKilometers(double distanceInMeters) {

double kilometers = distanceInMeters * 0.001;

System.out.println(distanceInMeters + " meters is equivalent to " + kilometers + " kilometers.");

}

public static void convertToInches(double distanceInMeters) {

double inches = distanceInMeters * 39.37;

System.out.println(distanceInMeters + " meters is equivalent to " + inches + " inches.");

}

public static void convertToFeet(double distanceInMeters) {

double feet = distanceInMeters * 3.281;

System.out.println(distanceInMeters + " meters is equivalent to " + feet + " feet.");

}

}

Step-by-step explanation:

In this program, we use a Scanner to get input from the user for the distance in meters. We then display a menu of selections using the displayMenu() method, and use a do-while loop to repeatedly prompt the user for their choice until they choose to quit (by entering 'd'). The user's choice is then passed to a switch statement, which calls the appropriate conversion method based on the selected option ('a', 'b', or 'c'). The conversion methods (convertToKilometers(), convertToInches(), and convertToFeet()) perform the respective conversions and display the results.

User Frandy
by
8.4k points