import java.util.Scanner; /** * 温度转换程序:实现摄氏温度与华氏温度的互相转换 * 支持控制台输入交互、命令行参数运行模式 */ public class TemperatureConverter { /** * 摄氏温度 转 华氏温度 * @param celsius 输入的摄氏温度值 * @return 转换后的华氏温度值,公式:F = C × 1.8 + 32 */ public static double celsiusToFahrenheit(double celsius) { return celsius * 1.8 + 32; } /** * 华氏温度 转 摄氏温度 * @param fahrenheit 输入的华氏温度值 * @return 转换后的摄氏温度值,公式:C = (F - 32) / 1.8 */ public static double fahrenheitToCelsius(double fahrenheit) { return (fahrenheit - 32) / 1.8; } /** * 主方法:程序入口,支持两种运行模式 * 1. 无参数:控制台交互式输入 * 2. 带参数:命令行参数模式 java TemperatureConverter 数值 温度类型(C/F) * @param args 命令行参数 */ public static void main(String[] args) { // 命令行参数模式 if (args.length == 2) { try { double temp = Double.parseDouble(args[0]); String type = args[1].toUpperCase(); if (type.equals("C")) { double res = celsiusToFahrenheit(temp); System.out.printf("%.2f ℃ = %.2f ℉%n", temp, res); } else if (type.equals("F")) { double res = fahrenheitToCelsius(temp); System.out.printf("%.2f ℉ = %.2f ℃%n", temp, res); } else { System.out.println("温度类型仅支持 C(摄氏) / F(华氏)"); } } catch (Exception e) { System.out.println("参数格式错误,示例:java TemperatureConverter 36.6 C"); } return; } // 控制台交互模式 Scanner scanner = new Scanner(System.in); System.out.println("===== 温度转换器 ====="); System.out.println("1. 摄氏温度转华氏温度"); System.out.println("2. 华氏温度转摄氏温度"); System.out.print("请选择功能(1/2):"); int choice = scanner.nextInt(); System.out.print("请输入温度数值:"); double value = scanner.nextDouble(); if (choice == 1) { double result = celsiusToFahrenheit(value); System.out.printf("转换结果:%.2f ℃ = %.2f ℉%n", value, result); } else if (choice == 2) { double result = fahrenheitToCelsius(value); System.out.printf("转换结果:%.2f ℉ = %.2f ℃%n", value, result); } else { System.out.println("输入选项错误!"); } scanner.close(); } }