import java.util.Scanner;//导入输入工具 public class Tempconvert {//类名与文件名相等 public static float c2f(float c) { return c * 9 / 5 + 32;//定义摄氏度转华氏度函数 } public static float f2c(float f) { return (f - 32) * 5 / 9;//定义华氏度转摄氏度函数 } public static void main(String[] args) { Scanner sc = new Scanner(System.in);//打开输入通道(固定) System.out.println("请输入要转换的温度与单位(例如 36.6 C 或 97 F)");//写提示语 String input = sc.nextLine(); // 接收输入 sc.close(); if (input.isEmpty()) {//处理空输入 System.out.println("输入为空,程序退出。"); return; }// String[] parts = input.split(" ");//将输入的字符串按空格分割成字符串数组 float wd; String dw; try { wd = Float.parseFloat(parts[0]);//将数组第一个元素(数值字符串)转为 float,赋值给 wd dw = parts.length > 1 ? parts[1].toUpperCase() : "C";// } catch (Exception e) {//如果数组长度 > 1,则取第二个元素并转大写赋值给 dw;否则默认单位为 "C" System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C");// return; } float result;//定义两个变量:result 用于保存转换后的温度值。 String resultUnit;//resultUnit 用于保存转换后的单位 if (dw.equals("C")) {//判断单位 dw 是否以 "C" 开头 result = c2f(wd); resultUnit = "F"; } else if (dw.equals("F")) {//若单位是“F” result = f2c(wd); resultUnit = "C"; } else {//未知单位 System.out.println("未知单位,请使用 C 或 F"); return; } // 修正:使用 printf 格式化输出 System.out.printf("转换结果:%.1f %s%n", result, resultUnit); } }