//TIP 要运行代码,请按 或 // 点击装订区域中的 图标。 import java.util.Scanner; public class TemperatureConverter { /** * 将摄氏度转换为华氏度。 * * @param c 摄氏温度 * @return 对应的华氏温度 */ public static double celsiusToFahrenheit(double c) { return c * 9.0 / 5.0 + 32.0; } /** * 将华氏度转换为摄氏度。 * * @param f 华氏温度 * @return 对应的摄氏温度 */ public static double fahrenheitToCelsius(double f) { return (f - 32.0) * 5.0 / 9.0; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):"); String input = scanner.nextLine().trim(); if (input.isEmpty()) { System.out.println("输入为空,程序退出。"); scanner.close(); return; } // 使用正则表达式增强解析能力(兼容 "36.6C"、"97 F" 等) input = input.replaceAll("\\s+", " "); // 合并多个空格为一个 String[] parts = input.split(" "); double value; String unit; try { if (parts.length == 1) { // 尝试从单个字符串中提取数字和单位(如 "36.6C") String s = parts[0]; int i = 0; while (i < s.length() && (Character.isDigit(s.charAt(i)) || s.charAt(i) == '.' || s.charAt(i) == '+' || s.charAt(i) == '-')) { i++; } if (i == 0 || i == s.length()) { throw new NumberFormatException("无法解析数值或单位"); } value = Double.parseDouble(s.substring(0, i)); unit = s.substring(i).toUpperCase().trim(); } else if (parts.length >= 2) { value = Double.parseDouble(parts[0]); unit = parts[1].toUpperCase().trim(); } else { throw new IllegalArgumentException("输入格式不正确"); } } catch (Exception e) { System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C"); scanner.close(); return; } 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("未知单位,请使用 C 或 F。"); } scanner.close(); } }