diff --git a/W1-徐洁娴-202506050222/README.md b/W1-徐洁娴-202506050222/README.md new file mode 100644 index 0000000..3a6a2b6 --- /dev/null +++ b/W1-徐洁娴-202506050222/README.md @@ -0,0 +1,13 @@ +# 温度转换程序(Java版) +## 项目简介 +本项目是基于Python温度转换程序移植的Java版本,实现了**摄氏度(C)与华氏度(F)之间的双向转换**,保留了原程序的交互逻辑、异常处理和注释规范,便于学习与维护。 +## 功能说明 +- 支持控制台交互输入,输入格式为「数值 + 单位」(示例:`36.6 C` 或 `97 F`) +- 单位不区分大小写,无单位时默认按摄氏度(C)处理 +- 结果保留2位小数输出 +- 处理空输入、格式错误、未知单位等异常场景并给出友好提示 +## 编译与运行命令 +在代码所在目录打开命令行,执行以下命令: +### 编译 + ```bash + javac TemperatureConverter.java \ No newline at end of file diff --git a/W1-徐洁娴-202506050222/TemperatureConverter.java b/W1-徐洁娴-202506050222/TemperatureConverter.java new file mode 100644 index 0000000..607dbfe --- /dev/null +++ b/W1-徐洁娴-202506050222/TemperatureConverter.java @@ -0,0 +1,57 @@ +import java.util.Scanner; +/** + * 温度转换器示例程序(Java) + * 支持摄氏度(C)与华氏度(F)之间互转 + */ +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) { + // 提示用户输入,格式示例:"36.6 C" 或 "97 F" + Scanner scanner = new Scanner(System.in); + System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):"); + String s = scanner.nextLine().trim(); + scanner.close(); + if (s.isEmpty()) { + System.out.println("输入为空,程序退出。"); + return; + } + String[] parts = s.split(" "); + try { + // 允许用户输入两个部分:数值与单位 + double value = Double.parseDouble(parts[0]); + String unit = parts.length > 1 ? parts[1].toUpperCase() : "C"; + 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。"); + } + } catch (Exception e) { + System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C"); + } + } +} \ No newline at end of file diff --git a/W1-徐洁娴-202506050222/屏幕截图 2026-03-09 121702.png b/W1-徐洁娴-202506050222/屏幕截图 2026-03-09 121702.png new file mode 100644 index 0000000..452eb57 Binary files /dev/null and b/W1-徐洁娴-202506050222/屏幕截图 2026-03-09 121702.png differ