Start by creating a new Java file:
Declare the Main Class:
public class Main {
}
Add the main Method:
public static void main(String[] args) {
}
Import the Scanner Class:
import java.util.Scanner;
Create a Scanner Object:
Scanner scanner = new Scanner(System.in);
Print the Menu:
System.out.println("Temperature Converter");
System.out.println("1. Celsius to Fahrenheit");
System.out.println("2. Celsius to Kelvin");
System.out.println("3. Fahrenheit to Celsius");
System.out.println("4. Fahrenheit to Kelvin");
System.out.println("5. Kelvin to Celsius");
System.out.println("6. Kelvin to Fahrenheit");
System.out.print("Choose an option (1-6): ");
After displaying the menu, you need to read the user’s choice. This reads an integer from the user, which represents their choice:
int choice = scanner.nextInt();
Read the Temperature:
System.out.print("Enter the temperature: ");
double temperature = scanner.nextDouble();
Write Conversion Methods:
public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9/5) + 32;
}
public static double celsiusToKelvin(double celsius) {
return celsius + 273.15;
}
public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
public static double fahrenheitToKelvin(double fahrenheit) {
return (fahrenheit - 32) * 5/9 + 273.15;
}
public static double kelvinToCelsius(double kelvin) {
return kelvin - 273.15;
}
public static double kelvinToFahrenheit(double kelvin) {
return (kelvin - 273.15) * 9/5 + 32;
}
Check the User’s Choice:
if (choice == 1) {
System.out.printf("%.2f Celsius = %.2f Fahrenheit%n", temperature, celsiusToFahrenheit(temperature));
} else if (choice == 2) {
System.out.printf("%.2f Celsius = %.2f Kelvin%n", temperature, celsiusToKelvin(temperature));
} else if (choice == 3) {
System.out.printf("%.2f Fahrenheit = %.2f Celsius%n", temperature, fahrenheitToCelsius(temperature));
} else if (choice == 4) {
System.out.printf("%.2f Fahrenheit = %.2f Kelvin%n", temperature, fahrenheitToKelvin(temperature));
} else if (choice == 5) {
System.out.printf("%.2f Kelvin = %.2f Celsius%n", temperature, kelvinToCelsius(temperature));
} else if (choice == 6) {
System.out.printf("%.2f Kelvin = %.2f Fahrenheit%n", temperature, kelvinToFahrenheit(temperature));
} else {
System.out.println("Invalid choice!");
}
It’s good practice to close the Scanner when you’re done using it:
scanner.close();