/** * 温度转换程序 * 功能:摄氏温度与华氏温度相互转换 * 支持交互式输入 + 命令行参数模式(加分项1) */ public class TemperatureConverter { /** * 摄氏温度转换为华氏温度 * @param c 摄氏温度值 * @return 转换后的华氏温度 */ public static double cToF(double c) { return c * 9.0 / 5.0 + 32; } /** * 华氏温度转换为摄氏温度 * @param f 华氏温度值 * @return 转换后的摄氏温度 */ public static double fToC(double f) { return (f - 32) * 5.0 / 9.0; } /** * 主方法:程序入口 * 支持两种模式: * 1. 无参数:交互式输入转换 * 2. 带两个参数:命令行直接转换(加分项) */ public static void main(String[] args) { // 加分项:命令行参数模式,格式:java TemperatureConverter 36.6 C if (args.length == 2) { try { double value = Double.parseDouble(args[0]); String unit = args[1]; if (unit.equalsIgnoreCase("C")) { double f = cToF(value); System.out.printf("%.2f°C = %.2f°F%n", value, f); } else if (unit.equalsIgnoreCase("F")) { double c = fToC(value); System.out.printf("%.2f°F = %.2f°C%n", value, c); } else { System.out.println("单位只能是 C 或 F"); } } catch (NumberFormatException e) { System.out.println("第一个参数必须是数字"); } return; } // 普通交互模式 java.util.Scanner sc = new java.util.Scanner(System.in); System.out.println("温度转换程序"); System.out.println("请输入温度和单位(例如:36.6 C),输入exit退出"); while (true) { System.out.print("请输入:"); String line = sc.nextLine().trim(); if (line.equalsIgnoreCase("exit")) { System.out.println("程序结束"); break; } String[] parts = line.split("\\s+"); if (parts.length != 2) { System.out.println("输入格式不正确,请重新输入"); continue; } try { double v = Double.parseDouble(parts[0]); String u = parts[1]; if (u.equalsIgnoreCase("C")) { System.out.printf("%.2f°C = %.2f°F%n", v, cToF(v)); } else if (u.equalsIgnoreCase("F")) { System.out.printf("%.2f°F = %.2f°C%n", v, fToC(v)); } else { System.out.println("单位错误,只能是 C 或 F"); } } catch (NumberFormatException e) { System.out.println("温度必须是数字"); } } sc.close(); } }