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.

118 lines
4.2 KiB

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
* 温度转换程序:实现摄氏温度与华氏温度的相互转换
* 支持交互式输入、命令行参数和批量文件转换三种模式
*/
public class TemperatureConverter {
/**
* 将摄氏温度转换为华氏温度
* @param celsius 摄氏温度值
* @return 对应的华氏温度值
*/
public static double celsiusToFahrenheit(double celsius) {
return celsius * 9.0 / 5.0 + 32.0;
}
/**
* 将华氏温度转换为摄氏温度
* @param fahrenheit 华氏温度值
* @return 对应的摄氏温度值
*/
public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32.0) * 5.0 / 9.0;
}
/**
* 解析并转换单个温度输入
* @param input 带单位的温度字符串,如 "36.6C" 或 "98.6F"
*/
public static void convertAndPrint(String input) {
try {
char unit = input.charAt(input.length() - 1);
double value = Double.parseDouble(input.substring(0, input.length() - 1));
if (unit == 'C' || unit == 'c') {
double fahrenheit = celsiusToFahrenheit(value);
System.out.printf("%.2f°C = %.2f°F%n", value, fahrenheit);
} else if (unit == 'F' || unit == 'f') {
double celsius = fahrenheitToCelsius(value);
System.out.printf("%.2f°F = %.2f°C%n", value, celsius);
} else {
System.out.println("错误:温度单位必须是 C 或 F");
}
} catch (NumberFormatException e) {
System.out.println("错误:无法解析温度数值,请输入如 36.6C 或 98.6F 的格式");
} catch (StringIndexOutOfBoundsException e) {
System.out.println("错误:输入不能为空或格式不正确");
}
}
/**
* 从文件批量读取温度并转换
* @param filename 输入文件名,每行一个温度值
*/
public static void batchConvertFromFile(String filename) {
try {
File file = new File(filename);
Scanner scanner = new Scanner(file);
int lineNumber = 0;
while (scanner.hasNextLine()) {
lineNumber++;
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
System.out.printf("第 %d 行: ", lineNumber);
convertAndPrint(line);
}
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("错误:未找到文件 " + filename);
}
}
/**
* 交互式转换模式
*/
public static void interactiveMode() {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎使用温度转换器");
System.out.println("输入格式:数字+单位(如 36.6C 或 98.6F),输入 exit 退出");
while (true) {
System.out.print("请输入温度: ");
String input = scanner.nextLine().trim();
if (input.equalsIgnoreCase("exit")) {
System.out.println("再见!");
break;
}
convertAndPrint(input);
}
scanner.close();
}
/**
* 主程序入口
* @param args 命令行参数:
* - 无参数:进入交互式模式
* - 一个参数:直接转换该温度(如 36.6C)
* - 两个参数且第一个为 -f:从指定文件批量转换
*/
public static void main(String[] args) {
if (args.length == 0) {
interactiveMode();
} else if (args.length == 1) {
convertAndPrint(args[0]);
} else if (args.length == 2 && args[0].equals("-f")) {
batchConvertFromFile(args[1]);
} else {
System.out.println("用法:");
System.out.println(" java TemperatureConverter - 进入交互式模式");
System.out.println(" java TemperatureConverter 36.6C - 直接转换单个温度");
System.out.println(" java TemperatureConverter -f temps.txt - 从文件批量转换");
}
}
}