Temperature conversion is a fundamental task in many scientific and engineering applications.
It involves converting temperatures from one unit to another, typically between Celsius and Fahrenheit.
This can be particularly useful in various fields, including meteorology, cooking, and engineering.
Objectives
- Understand the relationship between Celsius and Fahrenheit temperatures.
- Implement a Java program to convert temperatures between these two scales.
- Gain experience with basic input/output in Java.
Java Code
import java.util.Scanner;
public class TemperatureConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Temperature Converter");
System.out.print("Enter temperature: ");
double temperature = scanner.nextDouble();
System.out.print("Convert to (C/F): ");
char convertTo = scanner.next().toUpperCase().charAt(0);
if (convertTo == 'C') {
double celsius = (temperature - 32) * 5 / 9;
System.out.printf("%.2f Fahrenheit is %.2f Celsius%n", temperature, celsius);
} else if (convertTo == 'F') {
double fahrenheit = (temperature * 9 / 5) + 32;
System.out.printf("%.2f Celsius is %.2f Fahrenheit%n", temperature, fahrenheit);
} else {
System.out.println("Invalid option. Please enter 'C' or 'F'.");
}
scanner.close();
}
}
Program Structure and How to Run
The TemperatureConverter
class contains a main
method, which is the entry point of the program.
The program uses the Scanner
class for user input. Here’s a breakdown of the structure:
import java.util.Scanner;
: This imports the Scanner class for reading input from the user.public class TemperatureConverter
: This defines the class.public static void main(String[] args)
: The main method where the program execution begins.Scanner scanner = new Scanner(System.in);
: Creates a Scanner object to read input from the console.- The program prompts the user for a temperature and the desired conversion unit (C or F).
- It calculates the converted temperature based on user input and displays the result.
- Finally, the Scanner is closed to prevent resource leaks.
Running the Program
To run this program, follow these steps:
- Copy the code into a text editor and save it as
TemperatureConverter.java
. - Open your terminal or command prompt.
- Navigate to the directory where you saved the file.
- Compile the program using the command:
javac TemperatureConverter.java
- Run the compiled program with the command:
java TemperatureConverter
- Follow the prompts to input the temperature and conversion unit.