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.
88 lines
3.0 KiB
88 lines
3.0 KiB
package test1;
|
|
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;
|
|
}
|
|
|
|
/**
|
|
* 主方法,提供交互式转换功能。也支持命令行参数模式。
|
|
*
|
|
* @param args 命令行参数。如果提供两个参数(数值 单位),则直接转换并退出。
|
|
* 若没有则进入交互式模式。
|
|
*/
|
|
public static void main(String[] args) {
|
|
// 处理命令行参数模式
|
|
if (args.length == 2) {
|
|
processConversion(args[0], args[1].toUpperCase());
|
|
return;
|
|
} else if (args.length > 0) {
|
|
System.out.println("用法: java test1.ke1 [<温度值> <单位>]");
|
|
System.out.println("示例: java test1.ke1 36.6 C");
|
|
return;
|
|
}
|
|
|
|
// 交互式模式
|
|
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;
|
|
}
|
|
|
|
String[] parts = input.split("\\s+");
|
|
if (parts.length < 2) {
|
|
System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C");
|
|
scanner.close();
|
|
return;
|
|
}
|
|
|
|
processConversion(parts[0], parts[1].toUpperCase());
|
|
scanner.close();
|
|
}
|
|
|
|
/**
|
|
* 处理转换逻辑的核心方法。
|
|
*
|
|
* @param valueStr 温度值的字符串形式
|
|
* @param unit 单位字符串("C" 或 "F")
|
|
*/
|
|
private static void processConversion(String valueStr, String unit) {
|
|
try {
|
|
double value = Double.parseDouble(valueStr);
|
|
|
|
if (unit.startsWith("C")) {
|
|
// 从摄氏度转换为华氏度
|
|
double f = celsiusToFahrenheit(value);
|
|
System.out.printf("%.1f °C = %.2f °F%n", value, f);
|
|
} else if (unit.startsWith("F")) {
|
|
// 从华氏度转换为摄氏度
|
|
double c = fahrenheitToCelsius(value);
|
|
System.out.printf("%.1f °F = %.2f °C%n", value, c);
|
|
} else {
|
|
System.out.println("未知单位,请使用 C 或 F。");
|
|
}
|
|
} catch (NumberFormatException e) {
|
|
System.out.println("输入解析失败,温度值必须是一个有效的数字。");
|
|
}
|
|
}
|
|
}
|
|
|