4 changed files with 38 additions and 0 deletions
@ -0,0 +1,38 @@ |
|||||
|
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(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
Binary file not shown.
Binary file not shown.
|
After Width: | Height: | Size: 314 KiB |
Loading…
Reference in new issue