From 383494d52610e93a9693f7fbd770c161e953dc3f Mon Sep 17 00:00:00 2001 From: Mengxinyao Date: Sun, 5 Apr 2026 11:29:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(w1):W1-=E5=AD=9F=E9=91=AB=E5=9E=9A-2025060?= =?UTF-8?q?10204?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- w1/TemperatureConverter.java | 83 ++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 w1/TemperatureConverter.java diff --git a/w1/TemperatureConverter.java b/w1/TemperatureConverter.java new file mode 100644 index 0000000..c8ac76e --- /dev/null +++ b/w1/TemperatureConverter.java @@ -0,0 +1,83 @@ +//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(); + } +} \ No newline at end of file