Java program to convert liters to gallons.
Problem Statement
Write a Java program to convert liters to gallons. Given that one liter is equal to 0.264 gallons. The mathematical conversion equation to convert is as follows:
IPO(Input, Processing, Output )
IPO chart for the program is shown below:
Input for the program: amount in liters.
Processing
gallons = liters * 0.264
Round the output to 3 decimals.
Output: Print the gallons.
Tools Used
We will use the below tools to develop the program.
- JDK ( Java Development Kit)
- Eclipse IDE( Integrated Development Environment)
Eclipse IDE Setup
Some steps and instructions to create a Java application on Eclipse IDE:
- Create Java Project in Eclipse
https://www.testingdocs.com/create-a-new-java-project-in-eclipse/
- Create Java Package in Eclipse
https://www.testingdocs.com/create-java-package-in-eclipse-ide/
- Create Java Class in Eclipse
https://www.testingdocs.com/create-a-new-java-class-in-a-project/
- Run Java Project in Eclipse
https://www.testingdocs.com/run-java-project-in-eclipse/
Java program
/** * Java program to convert liters to gallons */ package questions; import java.util.Scanner; /** * @author * */ public class LitersToGallonsJavaProgram { /** * @param args */ public static void main(String[] args) { // variables double liters; // liters double gallons; // gallons char choice='y'; Scanner keyboard = new Scanner( System.in ); while(choice=='y' || choice== 'Y') { System.out.print( "Enter liters to convert to gallons:= " ); liters = keyboard.nextDouble( ); // 1 Liter = 0.264 Gallons. gallons = 0.264 * liters; System.out.print( liters + " Liters = " ); System.out.println( (double)Math.round(gallons * 1000d) / 1000d + " gallons." ); System.out.print( "Do you want to convert another amount? [y/n]:= " ); choice = keyboard.next().charAt(0); } keyboard.close(); } // end main } //end class
Screenshot
Screenshot of the program code in the IDE window.
Output
Save the program code and execute test cases to verify the program output.
Enter liters to convert to gallons:= 1
1.0 Liters = 0.264 gallons.
Do you want to convert another amount? [y/n]:= y
Enter liters to convert to gallons:= 3.785
3.785 Liters = 0.999 gallons.
Do you want to convert another amount? [y/n]:= n
The program will loop and continue to compute the conversion while the user enters either y or Y as specified in the loop condition.
—
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :