-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemperatureConverter.java
More file actions
44 lines (36 loc) · 1.71 KB
/
TemperatureConverter.java
File metadata and controls
44 lines (36 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.Scanner;
public class TemperatureConverter {
// Method to convert Celsius to Fahrenheit
public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
// Method to convert Fahrenheit to Celsius
public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
public static void main(String[] args) {
// Create a Scanner object to read input
Scanner scanner = new Scanner(System.in);
// Prompt the user for the temperature value
System.out.print("Enter the temperature value: ");
double temperature = scanner.nextDouble();
// Prompt the user for the unit of measurement (C for Celsius, F for Fahrenheit)
System.out.print("Enter the unit of measurement (C for Celsius, F for Fahrenheit): ");
char unit = scanner.next().charAt(0);
// Convert and display the result based on the unit
if (unit == 'C' || unit == 'c') {
// Convert from Celsius to Fahrenheit
double fahrenheit = celsiusToFahrenheit(temperature);
System.out.printf("%.2f Celsius is equal to %.2f Fahrenheit.%n", temperature, fahrenheit);
} else if (unit == 'F' || unit == 'f') {
// Convert from Fahrenheit to Celsius
double celsius = fahrenheitToCelsius(temperature);
System.out.printf("%.2f Fahrenheit is equal to %.2f Celsius.%n", temperature, celsius);
} else {
// If the user enters an invalid unit
System.out.println("Invalid unit. Please enter 'C' for Celsius or 'F' for Fahrenheit.");
}
// Close the scanner
scanner.close();
}
}