ScriptCrew

Temperature Converter

Niharika

Step-by-Step Instructions

Step 1: Create the Main Structure

Start by creating a new Java file:

  1. Open your text editor or IDE.
  2. Create a new file named Main.java.

Declare the Main Class:

 public class Main {
           
  }

Add the main Method:

public static void main(String[] args) {
            
 }

Step 2: Set Up User Input

Import the Scanner Class:

import java.util.Scanner; 

Create a Scanner Object:

Scanner scanner = new Scanner(System.in);

Step 3: Display Menu Options

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): ");

Step 4: Get User Input

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();

Step 5: Perform the Conversion

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;
}
            

Step 6: Use Conditional Statements

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!");
}

Step 7: Close the Scanner

It’s good practice to close the Scanner when you’re done using it:

scanner.close();