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.
38 lines
1.5 KiB
38 lines
1.5 KiB
import java.util.Scanner;
|
|
public class TemperatureConverter{
|
|
public static double celsiusToFahrenheit(double celsius){
|
|
return celsius * 9.0/5.0 + 32.0;
|
|
}
|
|
public static double fahrenheitToCelsius(double fahrenheit){
|
|
return (fahrenheit - 32.0) * 5.0 / 9.0;
|
|
}
|
|
public static void main(String[] args){
|
|
Scanner scanner = new Scanner(System.in);
|
|
System.out.print("请输入要转换的温度与单位:");
|
|
String input = scanner.nextLine().trim();
|
|
if (input.isEmpty()){
|
|
System.out.println("输入为空,程序退出。");
|
|
return;
|
|
}
|
|
try{
|
|
double value = Double.parseDouble(parts[0]);
|
|
String unit = 'C';
|
|
if (parts.length > 1){
|
|
unit = parts[1].toUpperCase();
|
|
}
|
|
if (unit.startsWith('C')){
|
|
double f = celsiusToFahrenheit(value);
|
|
System.out.printf("%.1f℃ = %.2f℉%n",value,f);
|
|
} else if (unit.startsWith("F")){
|
|
double c = fahrenheitToCelsius(value);
|
|
System.out.println("未知单位,请使用C或F。");
|
|
}
|
|
} catch (NumberFormatExpectation e){
|
|
System.out.println("输入解析失败,请按示例输入数值与单位。");
|
|
} catch (Expectation e){
|
|
System.out.println("输入格式错误,请检查输入。");
|
|
} finally {
|
|
scanner,close();
|
|
}
|
|
}
|
|
}
|