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.
49 lines
1.9 KiB
49 lines
1.9 KiB
import java.util.Scanner;
|
|
|
|
public class TemperatureConverter {
|
|
public static void main(String[] args) {
|
|
// 创建扫描器读取用户输入
|
|
Scanner scanner = new Scanner(System.in);
|
|
System.out.println("=== 温度转换器 ===");
|
|
System.out.println("请输入温度和单位 (例如: 25 C 或 77 F):");
|
|
|
|
// 读取整行输入
|
|
String input = scanner.nextLine();
|
|
|
|
// 使用空格分割输入为数组 [温度值, 单位]
|
|
String[] parts = input.split(" ");
|
|
|
|
// 检查输入是否合法 (必须包含至少两部分)
|
|
if (parts.length < 2) {
|
|
System.out.println("输入格式错误!请使用格式: 数字 单位 (例如 100 C)");
|
|
return; // 结束程序
|
|
}
|
|
|
|
try {
|
|
// 1. 解析温度数值 (取数组第0个元素)
|
|
float value = Float.parseFloat(parts[0]);
|
|
|
|
// 2. 获取并转换单位 (取数组第1个元素,并转为大写以统一处理)
|
|
String unit = parts[1].toUpperCase();
|
|
|
|
// 3. 根据单位进行转换
|
|
if (unit.equals("C")) {
|
|
float fahrenheit = (value * 9 / 5) + 32;
|
|
System.out.printf("%.2f°C = %.2f°F\n", value, fahrenheit);
|
|
} else if (unit.equals("F")) {
|
|
float celsius = (value - 32) * 5 / 9;
|
|
System.out.printf("%.2f°F = %.2f°C\n", value, celsius);
|
|
} else {
|
|
System.out.println("不支持的单位: " + parts[1]);
|
|
System.out.println("请输入 C (摄氏度) 或 F (华氏度)");
|
|
}
|
|
|
|
} catch (NumberFormatException e) {
|
|
System.out.println("数值解析错误!请确保第一个输入是数字。");
|
|
} catch (ArrayIndexOutOfBoundsException e) {
|
|
System.out.println("输入参数不足!");
|
|
}
|
|
|
|
scanner.close();
|
|
}
|
|
}
|