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.

82 lines
3.2 KiB

import java.util.Scanner;
/**
* 温度转换工具类
* 功能:实现摄氏温度(C)与华氏温度(F)之间的双向转换
* 转换公式:
* - 摄氏转华氏:F = C × 9/5 + 32
* - 华氏转摄氏:C = (F - 32) × 5/9
*/
public class TemperatureConverter {
/**
* 摄氏温度转换为华氏温度
* @param celsius 摄氏温度值(double类型)
* @return 转换后的华氏温度值(double类型)
*/
public static double celsiusToFahrenheit(double celsius) {
return celsius * 9.0 / 5.0 + 32;
}
/**
* 华氏温度转换为摄氏温度
* @param fahrenheit 华氏温度值(double类型)
* @return 转换后的摄氏温度值(double类型)
*/
public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5.0 / 9.0;
}
/**
* 主方法:程序入口
* 支持两种运行模式:
* 1. 命令行参数模式:java TemperatureConverter 数值 单位(如 C/F)
* 2. 交互模式:无命令行参数时,控制台输入温度和单位
* @param args 命令行参数数组
*/
public static void main(String[] args) {
// 处理命令行参数模式
if (args.length == 2) {
try {
double tempValue = Double.parseDouble(args[0]);
String unit = args[1].toUpperCase(); // 统一转为大写,兼容小写输入
if (unit.equals("C")) {
double fahrenheit = celsiusToFahrenheit(tempValue);
System.out.printf("%.2f 摄氏度 = %.2f 华氏度%n", tempValue, fahrenheit);
} else if (unit.equals("F")) {
double celsius = fahrenheitToCelsius(tempValue);
System.out.printf("%.2f 华氏度 = %.2f 摄氏度%n", tempValue, celsius);
} else {
System.err.println("单位错误!请输入 C(摄氏)或 F(华氏)");
}
} catch (NumberFormatException e) {
System.err.println("温度值格式错误!请输入有效的数字");
}
return;
}
// 交互模式(无命令行参数时)
Scanner scanner = new Scanner(System.in);
System.out.println("=== 温度转换程序 ===");
System.out.print("请输入温度值:");
double tempValue = scanner.nextDouble();
scanner.nextLine(); // 吸收换行符
System.out.print("请输入温度单位(C=摄氏,F=华氏):");
String unit = scanner.nextLine().toUpperCase();
// 根据单位执行转换并输出结果
if (unit.equals("C")) {
double fahrenheit = celsiusToFahrenheit(tempValue);
System.out.printf("转换结果:%.2f 摄氏度 = %.2f 华氏度%n", tempValue, fahrenheit);
} else if (unit.equals("F")) {
double celsius = fahrenheitToCelsius(tempValue);
System.out.printf("转换结果:%.2f 华氏度 = %.2f 摄氏度%n", tempValue, celsius);
} else {
System.out.println("输入的单位无效!请重新运行程序并输入 C 或 F");
}
scanner.close();
}
}