Write a java program to convert car consumption from one unit to another. Offer the user the choice of either conversion, kpl to mpg or mpg to kpl. The interface should be: PREFERRED CONVERSION: 1. kpl to mpg 2. mpg to kpl Enter your choice: 2 Enter miles per gallon value: mpg_value The equivalent kilometers per liter is: kpl_value Use the constants 1 mile = 1609 meters and 1 gallon = 3.785 liters. Useful formula: mpg = (kpl / 1.609) * 3.785 kpl = (mpg * 1.609) / 3.785 Note: the output of the program above should be formatted to 2 decimal places using the method System.out.printf(). Note: Use switch Control statement
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("\n1. kpl to mpg \n2. mpg to kpl\nEnter your choice: ");
int c=in.nextInt();
switch(c){
case 1:
double kpl_value;
System.out.print("Enter kpl value:");
kpl_value=in.nextDouble();
double mpg = (kpl_value / 1.609) * 3.785;
System.out.printf("The equivalent mpg is: %.2f", mpg);
break;
case 2:
double mpg_value;
System.out.print("Enter miles per gallon value:");
mpg_value=in.nextDouble();
double kpl = (mpg_value * 1.609) / 3.785;
System.out.printf("The equivalent kpl is: %.2f", kpl);
break;
default:
System.out.println("\nInvalid input");
}
}
}
Comments
Leave a comment