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.
90 lines
2.9 KiB
90 lines
2.9 KiB
import java.util.Scanner;
|
|
|
|
/**
|
|
* Temperature Converter (Java Version)
|
|
* Supports conversion between Celsius (C) and Fahrenheit (F).
|
|
*
|
|
* Features:
|
|
* 1. Interactive input, for example: 36.6 C or 97 F
|
|
* 2. Command-line argument mode, for example:
|
|
* java TemperatureConverter 36.6 C
|
|
*/
|
|
public class TemperatureConverter {
|
|
|
|
/**
|
|
* Converts Celsius to Fahrenheit.
|
|
*
|
|
* @param c temperature in Celsius
|
|
* @return equivalent temperature in Fahrenheit
|
|
*/
|
|
public static double celsiusToFahrenheit(double c) {
|
|
return c * 9.0 / 5.0 + 32.0;
|
|
}
|
|
|
|
/**
|
|
* Converts Fahrenheit to Celsius.
|
|
*
|
|
* @param f temperature in Fahrenheit
|
|
* @return equivalent temperature in Celsius
|
|
*/
|
|
public static double fahrenheitToCelsius(double f) {
|
|
return (f - 32.0) * 5.0 / 9.0;
|
|
}
|
|
|
|
/**
|
|
* Main method of the program.
|
|
*
|
|
* Input examples:
|
|
* 1. Interactive mode: 36.6 C
|
|
* 2. Command-line mode: java TemperatureConverter 36.6 C
|
|
*
|
|
* @param args command-line arguments
|
|
*/
|
|
public static void main(String[] args) {
|
|
String input;
|
|
|
|
// If command-line arguments are provided, use them first
|
|
if (args.length > 0) {
|
|
StringBuilder sb = new StringBuilder();
|
|
for (String arg : args) {
|
|
sb.append(arg).append(" ");
|
|
}
|
|
input = sb.toString().trim();
|
|
} else {
|
|
// Prompt the user for input, for example: "36.6 C" or "97 F"
|
|
Scanner scanner = new Scanner(System.in);
|
|
System.out.print("Enter the temperature and unit to convert (for example 36.6 C or 97 F): ");
|
|
input = scanner.nextLine().trim();
|
|
}
|
|
|
|
if (input.isEmpty()) {
|
|
System.out.println("Input is empty. Program terminated.");
|
|
return;
|
|
}
|
|
|
|
String[] parts = input.split("\\s+");
|
|
double value;
|
|
String unit;
|
|
|
|
try {
|
|
// Allow the user to enter a numeric value and a unit
|
|
value = Double.parseDouble(parts[0]);
|
|
unit = (parts.length > 1) ? parts[1].toUpperCase() : "C";
|
|
} catch (Exception e) {
|
|
System.out.println("Failed to parse input. Please enter a value and unit like: 36.6 C");
|
|
return;
|
|
}
|
|
|
|
if (unit.startsWith("C")) {
|
|
// Convert from Celsius to Fahrenheit
|
|
double f = celsiusToFahrenheit(value);
|
|
System.out.printf("%.1f °C = %.2f °F%n", value, f);
|
|
} else if (unit.startsWith("F")) {
|
|
// Convert from Fahrenheit to Celsius
|
|
double c = fahrenheitToCelsius(value);
|
|
System.out.printf("%.1f °F = %.2f °C%n", value, c);
|
|
} else {
|
|
System.out.println("Unknown unit. Please use C or F.");
|
|
}
|
|
}
|
|
}
|