1. Introduction
Converting temperatures between Fahrenheit and Celsius is a common requirement in many applications. This Java program demonstrates how to perform this conversion, providing an opportunity to work with user input, mathematical operations, and output formatting. The conversion formula from Fahrenheit to Celsius is Celsius = (Fahrenheit – 32) * 5/9.
2. Program Steps
1. Import the Scanner class from the java.util package for user input.
2. Define the main class named FahrenheitToCelsius.
3. Inside the main class, define the main method.
4. Inside the main method, create an object of the Scanner class to take user input.
5. Prompt the user to enter a temperature in Fahrenheit and store it in a variable.
6. Convert the temperature from Fahrenheit to Celsius using the formula Celsius = (Fahrenheit – 32) * 5/9.
7. Print the converted temperature to the console.
3. Code Program
import java.util.Scanner; // 1. Importing Scanner class for user input
public class FahrenheitToCelsius { // 2. Defining the main class
public static void main(String[] args) { // 3. Defining the main method
Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input
System.out.print("Enter temperature in Fahrenheit: "); // 5. Prompting user for temperature in Fahrenheit
double fahrenheit = input.nextDouble(); // Storing the Fahrenheit temperature in variable fahrenheit
double celsius = (fahrenheit - 32) * 5/9; // 6. Converting Fahrenheit to Celsius using the formula
System.out.println(fahrenheit + " Fahrenheit is equal to " + celsius + " Celsius"); // 7. Printing the converted temperature
input.close(); // Closing the Scanner object to avoid memory leak
}
}
Output:
Enter temperature in Fahrenheit: 98.6 98.6 Fahrenheit is equal to 37.0 Celsius
4. Step By Step Explanation
– Step 1: The Scanner class from the java.util package is imported, enabling the program to take user input.
– Step 2: The main class FahrenheitToCelsius is defined.
– Step 3: The main method is defined inside the main class, serving as the entry point of the Java program.
– Step 4: A Scanner object named "input" is created to read user input.
– Step 5: The user is prompted to enter a temperature in Fahrenheit, 98.6, which is then stored in the variable fahrenheit.
– Step 6: The program converts the temperature from Fahrenheit to Celsius using the formula Celsius = (Fahrenheit – 32) * 5/9, resulting in 37.0, which is stored in the variable celsius.
– Step 7: Finally, the converted temperature in Celsius is printed to the console.
– The Scanner object is then closed to prevent resource leak.