import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * 温度转换程序:实现摄氏(C)和华氏(F)温度双向转换 * 支持交互式输入、命令行参数、批量文件转换三种模式 */ public class TemperatureConverter { // 摄氏转华氏公式:F = C × 9/5 + 32 public static double celsiusToFahrenheit(double celsius) { return celsius * 9.0 / 5.0 + 32; } // 华氏转摄氏公式:C = (F - 32) × 5/9 public static double fahrenheitToCelsius(double fahrenheit) { return (fahrenheit - 32) * 5.0 / 9.0; } // 转换并打印结果 private static void convertAndPrint(double value, String unit) { if (unit.equalsIgnoreCase("C")) { double f = celsiusToFahrenheit(value); System.out.printf("%.2f °C = %.2f °F%n", value, f); } else if (unit.equalsIgnoreCase("F")) { double c = fahrenheitToCelsius(value); System.out.printf("%.2f °F = %.2f °C%n", value, c); } else { System.out.println("无效单位!请输入 C 或 F"); } } // 交互式输入模式(默认) private static void interactiveMode() { Scanner scanner = new Scanner(System.in); System.out.print("请输入温度和单位(例:33 C):"); String input = scanner.nextLine().trim(); String[] parts = input.split("\\s+"); if (parts.length != 2) { System.out.println("格式错误!请按「数值 单位」输入"); return; } try { double temp = Double.parseDouble(parts[0]); convertAndPrint(temp, parts[1]); } catch (NumberFormatException e) { System.out.println("数值错误!请输入数字"); } scanner.close(); } // 主方法:程序入口 public static void main(String[] args) { interactiveMode(); } }