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.

63 lines
2.3 KiB

import java.util.Scanner;
// 温度转换:摄氏 ↔ 华氏
public class TemperatureConverter {
// 摄氏转华氏
public static double c2f(double c) {
return c * 9 / 5 + 32;
}
// 华氏转摄氏
public static double f2c(double f) {
return (f - 32) * 5 / 9;
}
public static void main(String[] args) {
if (args.length >= 1) {
runWithArgs(args);
return;
}
Scanner sc = new Scanner(System.in);
System.out.print("输入温度和单位(如 36.6 C 或 97 F):");
String line = sc.nextLine().trim();
sc.close();
if (line.isEmpty()) {
System.out.println("输入为空,退出。");
return;
}
String[] parts = line.split(" ");
try {
double val = Double.parseDouble(parts[0]);
String unit = parts.length > 1 ? parts[1].toUpperCase() : "C";
if (unit.startsWith("C")) {
double f = c2f(val);
System.out.printf("%.2f °C = %.2f °F%n", val, f);
} else if (unit.startsWith("F")) {
double c = f2c(val);
System.out.printf("%.2f °F = %.2f °C%n", val, c);
} else {
System.out.println("单位不对,用 C 或 F。");
}
} catch (NumberFormatException e) {
System.out.println("输入不对,像这样:36.6 C");
}
}
// 处理命令行参数
private static void runWithArgs(String[] args) {
try {
double val = Double.parseDouble(args[0]);
String unit = args.length > 1 ? args[1].toUpperCase() : "C";
if (unit.startsWith("C")) {
double f = c2f(val);
System.out.printf("%.2f °C = %.2f °F%n", val, f);
} else if (unit.startsWith("F")) {
double c = f2c(val);
System.out.printf("%.2f °F = %.2f °C%n", val, c);
} else {
System.out.println("单位不对,用 C 或 F。");
}
} catch (NumberFormatException e) {
System.out.println("参数不对,像这样:java TemperatureConverter 36.6 C");
}
}
}