3 changed files with 123 additions and 0 deletions
@ -0,0 +1,5 @@ |
|||||
|
1.java基本框架和函数语法的学习 |
||||
|
2.if...else...语句的学习 |
||||
|
3.优化交互式代码,实现了命令行参数模式 |
||||
|
4.解决IDE提示“程序已在运行”的问题 |
||||
|
5.完善代码 |
||||
@ -0,0 +1,118 @@ |
|||||
|
**Java源码** |
||||
|
|
||||
|
import java.util.Scanner; |
||||
|
|
||||
|
public class TemperatureConverter { |
||||
|
|
||||
|
public static double celsiusToFahrenheit(double c){ |
||||
|
|
||||
|
return c\*9.0/5.0+32.0; |
||||
|
|
||||
|
} |
||||
|
|
||||
|
public static double fahrenheitToCelsius(double f){ |
||||
|
|
||||
|
return(f-32.0)\*5.0/9.0; |
||||
|
|
||||
|
} |
||||
|
|
||||
|
public static void main(String\[] args){ |
||||
|
|
||||
|
if (args.length>=2){ |
||||
|
|
||||
|
try{ |
||||
|
|
||||
|
double value=Double.parseDouble(args\[0]); |
||||
|
|
||||
|
String unit=args\[1].toUpperCase(); |
||||
|
|
||||
|
if(unit.startsWith("C")){ |
||||
|
|
||||
|
double f=celsiusToFahrenheit(value); |
||||
|
|
||||
|
System.out.printf("%.2f℃=%.2f℉%n",value,f); |
||||
|
|
||||
|
}else if (unit.startsWith("F")){ |
||||
|
|
||||
|
double c=fahrenheitToCelsius(value); |
||||
|
|
||||
|
System.out.printf("%.2f℉=%.2f℃%n",value,c); |
||||
|
|
||||
|
}else { |
||||
|
|
||||
|
System.out.println("未知单位,请使用 C 或 F。"); |
||||
|
|
||||
|
} |
||||
|
|
||||
|
}catch(Exception e){ |
||||
|
|
||||
|
System.out.println("命令行解析失败,请按示例输入,例如:java TemperatureConverter 36.6 C"); |
||||
|
|
||||
|
} |
||||
|
|
||||
|
}else{ |
||||
|
|
||||
|
mainLogic(); |
||||
|
|
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
public static void mainLogic(){ |
||||
|
|
||||
|
Scanner scanner=new Scanner(System.in); |
||||
|
|
||||
|
System.out.print("请输入要转换的温度与单位(例如 36.6 C 或 97 F):"); |
||||
|
|
||||
|
String s=scanner.nextLine().trim(); |
||||
|
|
||||
|
if (s.isEmpty()){ |
||||
|
|
||||
|
System.out.println("'输入为空,程序退出。"); |
||||
|
|
||||
|
return; |
||||
|
|
||||
|
} |
||||
|
|
||||
|
String\[] parts=s.split("\\\\s+"); |
||||
|
|
||||
|
try{ |
||||
|
|
||||
|
double value=Double.parseDouble(parts\[0]); |
||||
|
|
||||
|
String unit=parts.length>1? parts\[1].toUpperCase():"C"; |
||||
|
|
||||
|
if (unit.startsWith("C")){ |
||||
|
|
||||
|
double f=celsiusToFahrenheit(value); |
||||
|
|
||||
|
System.out.printf("%.2f℃=%.2f℉%n",value,f); |
||||
|
|
||||
|
}else if(unit.startsWith("F")){ |
||||
|
|
||||
|
double c=fahrenheitToCelsius(value); |
||||
|
|
||||
|
System.out.printf("%.2f℉=%.2f℃%n",value,c); |
||||
|
|
||||
|
}else{ |
||||
|
|
||||
|
System.out.println("未知单位,请使用 C 或 F。"); |
||||
|
|
||||
|
} |
||||
|
|
||||
|
}catch(Exception e){ |
||||
|
|
||||
|
System.out.println("输入解析失败,请按示例输入数值与单位,例如:36.6 C"); |
||||
|
|
||||
|
}finally{ |
||||
|
|
||||
|
scanner.close(); |
||||
|
|
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
|
||||
|
|
||||
|
After Width: | Height: | Size: 312 KiB |
Loading…
Reference in new issue