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.
105 lines
3.6 KiB
105 lines
3.6 KiB
import java.util.Scanner;
|
|
import java.io.File;
|
|
import java.io.FileNotFoundException;
|
|
/**
|
|
* 温度转换器
|
|
* 支持摄氏度(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;
|
|
}
|
|
/**
|
|
* 统一执行温度转换并输出结果
|
|
* @param value 温度数值
|
|
* @param unit 温度单位(C/F)
|
|
*/
|
|
public static void convert(double value, String unit) {
|
|
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。");
|
|
}
|
|
}
|
|
/**
|
|
* 从文件批量读取温度并转换
|
|
* @param fileName 待读取的文件名
|
|
*/
|
|
public static void batchConvert(String fileName) {
|
|
try {
|
|
Scanner fileScanner = new Scanner(new File(fileName));
|
|
System.out.println("===== 批量转换结果 =====");
|
|
while (fileScanner.hasNextLine()) {
|
|
String line = fileScanner.nextLine().trim();
|
|
if (line.isEmpty()) continue;
|
|
String[] parts = line.split("\\s+");
|
|
double val = Double.parseDouble(parts[0]);
|
|
String unit = parts[1].toUpperCase();
|
|
convert(val, unit);
|
|
}
|
|
fileScanner.close();
|
|
} catch (FileNotFoundException e) {
|
|
System.out.println("文件不存在:" + fileName);
|
|
}
|
|
}
|
|
/**
|
|
* 程序主入口
|
|
*/
|
|
public static void main(String[] args) {
|
|
// 优先处理文件批量转换指令
|
|
if (args.length == 2 && args[0].equals("-file")) {
|
|
batchConvert(args[1]);
|
|
return;
|
|
}
|
|
// 处理普通命令行参数
|
|
if (args.length == 2) {
|
|
try {
|
|
double val = Double.parseDouble(args[0]);
|
|
String unit = args[1].toUpperCase();
|
|
convert(val, unit);
|
|
return;
|
|
} catch (Exception e) {
|
|
System.out.println("命令行参数错误!示例:36.6 C");
|
|
return;
|
|
}
|
|
}
|
|
// 交互模式(无参数时进入)
|
|
Scanner scanner = new Scanner(System.in);
|
|
System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):");
|
|
String s = scanner.nextLine().trim();
|
|
if (s.isEmpty()) {
|
|
System.out.println("输入为空,程序退出。");
|
|
return;
|
|
}
|
|
String[] parts = s.split(" ");
|
|
double value;
|
|
String unit;
|
|
try {
|
|
value = Double.parseDouble(parts[0]);
|
|
unit = parts.length > 1 ? parts[1].toUpperCase() : "C";
|
|
} catch (Exception e) {
|
|
System.out.println("输入解析失败,请按示例输入:36.6 C");
|
|
return;
|
|
}
|
|
convert(value, unit);
|
|
scanner.close();
|
|
}
|
|
}
|