You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

121 lines
4.5 KiB

import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
* 温度转换器程序(Java版)
* 支持摄氏度(C)与华氏度(F)之间互转
* 支持三种输入方式:
* 1. 交互式输入(控制台提示输入)
* 2. 命令行参数(例如:java TemperatureConverter 36.6 C)
* 3. 批量转换(从temps.txt文件读取多行温度)
*/
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;
}
/**
* 处理温度转换的核心逻辑
* @param value 温度数值
* @param unit 温度单位(C/F,不区分大小写)
*/
public static void convert(double value, String unit) {
String upperUnit = unit.toUpperCase();
if (upperUnit.equals("C")) {
double f = celsiusToFahrenheit(value);
System.out.printf("%.2f °C = %.2f °F%n", value, f);
} else if (upperUnit.equals("F")) {
double c = fahrenheitToCelsius(value);
System.out.printf("%.2f °F = %.2f °C%n", value, c);
} else {
System.out.println("未知单位,请使用 C 或 F。");
}
}
/**
* 交互式输入模式(和Python原版一致)
*/
public static void interactiveMode() {
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;
}
try {
String[] parts = s.split("\\s+");
double value = Double.parseDouble(parts[0]);
// 若用户只输数值,默认按摄氏度处理
String unit = parts.length > 1 ? parts[1] : "C";
convert(value, unit);
} catch (Exception e) {
System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C");
}
}
/**
* 批量转换:从文件读取多行温度并输出结果(加分项)
* @param filePath 文件路径(每行格式:数值 单位,例如 36.6 C)
*/
public static void batchConvert(String filePath) {
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
System.out.println("\n===== 批量转换开始 =====");
while ((line = br.readLine()) != null) {
String trimLine = line.trim();
// 跳过空行
if (trimLine.isEmpty()) continue;
try {
String[] parts = trimLine.split("\\s+");
double value = Double.parseDouble(parts[0]);
String unit = parts.length > 1 ? parts[1] : "C";
System.out.print("处理:" + line + " → ");
convert(value, unit);
} catch (Exception e) {
System.out.println("行「" + line + "」格式错误,跳过");
}
}
System.out.println("===== 批量转换结束 =====\n");
} catch (IOException e) {
System.out.println("\n读取文件失败:找不到 " + filePath + " 文件(请确认文件在同目录下)\n");
}
}
public static void main(String[] args) {
// 优先处理命令行参数模式(加分项)
if (args.length >= 2) {
try {
double value = Double.parseDouble(args[0]);
String unit = args[1];
convert(value, unit);
} catch (Exception e) {
System.out.println("命令行参数解析失败!示例用法:java TemperatureConverter 36.6 C");
}
} else {
// 无命令行参数则进入交互式模式 + 批量转换
interactiveMode();
batchConvert("temps.txt");
}
}
}