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.
92 lines
3.4 KiB
92 lines
3.4 KiB
import java.util.Scanner;
|
|
|
|
/**
|
|
* 温度转换器程序(Java版)
|
|
* 完全移植Python原版功能,支持摄氏度(C)与华氏度(F)互转
|
|
* 额外实现加分项:命令行参数模式,同时保留控制台交互模式
|
|
* @author 你的姓名-你的学号
|
|
*/
|
|
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.startsWith("C")) {
|
|
double f = celsiusToFahrenheit(value);
|
|
System.out.printf("%.2f °C = %.2f °F%n", value, f);
|
|
} else if (upperUnit.startsWith("F")) {
|
|
double c = fahrenheitToCelsius(value);
|
|
System.out.printf("%.2f °F = %.2f °C%n", value, c);
|
|
} else {
|
|
System.out.println("未知单位,请使用 C 或 F。");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 程序主入口方法
|
|
* 支持两种运行模式:
|
|
* 1. 命令行参数模式:java TemperatureConverter 36.6 C(加分项)
|
|
* 2. 控制台交互模式:无参数时进入,与Python原版交互逻辑一致
|
|
* @param args 命令行参数,可选为[温度数值, 单位]
|
|
*/
|
|
public static void main(String[] args) {
|
|
// 优先处理命令行参数模式
|
|
if (args.length >= 2) {
|
|
try {
|
|
double value = Double.parseDouble(args[0]);
|
|
String unit = args[1];
|
|
convert(value, unit);
|
|
return;
|
|
} catch (NumberFormatException e) {
|
|
System.out.println("命令行参数解析失败:数值格式错误,请输入浮点型数值");
|
|
System.out.println("使用示例:java TemperatureConverter 36.6 C");
|
|
return;
|
|
}
|
|
}
|
|
|
|
// 无命令行参数时,进入控制台交互模式(与Python原版一致)
|
|
Scanner scanner = new Scanner(System.in);
|
|
System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):");
|
|
String input = scanner.nextLine().strip();
|
|
scanner.close();
|
|
|
|
// 处理空输入
|
|
if (input.isEmpty()) {
|
|
System.out.println("输入为空,程序退出。");
|
|
return;
|
|
}
|
|
|
|
// 解析输入的数值和单位
|
|
String[] parts = input.split(" ");
|
|
try {
|
|
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");
|
|
}
|
|
}
|
|
}
|