You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.1 KiB

/**
* Temperature Converter Program
* Convert between Celsius and Fahrenheit
*/
public class TemperatureConverter {
/**
* Convert Celsius to Fahrenheit
*
* @param celsius Celsius temperature
* @return Fahrenheit temperature
*/
public static double celsiusToFahrenheit(double celsius) {
// Formula: Fahrenheit = Celsius * 9/5 + 32
return celsius * 9.0 / 5.0 + 32.0;
}
/**
* Convert Fahrenheit to Celsius
*
* @param fahrenheit Fahrenheit temperature
* @return Celsius temperature
*/
public static double fahrenheitToCelsius(double fahrenheit) {
// Formula: Celsius = (Fahrenheit - 32) * 5/9
return (fahrenheit - 32.0) * 5.0 / 9.0;
}
/**
* Main method - program entry point
*/
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
System.out.print("Please enter temperature and unit (e.g. 36.6 C or 97 F): ");
String s = scanner.nextLine().trim();
if (s.isEmpty()) {
System.out.println("Input is empty, program exit.");
scanner.close();
return;
}
String[] parts = s.split(" ");
try {
double value = Double.parseDouble(parts[0]);
String unit = (parts.length > 1) ? parts[1].toUpperCase() : "C";
if (unit.startsWith("C")) {
double f = celsiusToFahrenheit(value);
System.out.printf("%.2f C = %.2f F%n", value, f);
} else if (unit.startsWith("F")) {
double c = fahrenheitToCelsius(value);
System.out.printf("%.2f F = %.2f C%n", value, c);
} else {
System.out.println("Unknown unit, please use C or F.");
}
} catch (Exception e) {
System.out.println("Input error, please use format like: 36.6 C");
} finally {
scanner.close();
}
}
}