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.
37 lines
1.6 KiB
37 lines
1.6 KiB
import java.io.File;
|
|
import java.io.FileNotFoundException;
|
|
import java.util.Scanner;
|
|
public class TemperatureConverter{
|
|
public static double c2f(double c){return c*9/5+32;}
|
|
public static double f2c(double f){return (f-32)*5/9;}
|
|
public static void conv(String s){
|
|
s=s.trim();
|
|
if(s.isEmpty()){System.out.println("输入为空,跳过。");return;}
|
|
String[]a=s.split("\\s+");
|
|
try{
|
|
double v=Double.parseDouble(a[0]);
|
|
String u=a.length>1?a[1].toUpperCase():"C";
|
|
if(u.startsWith("C"))System.out.printf("%.1f°C=%.2f°F%n",v,c2f(v));
|
|
else if(u.startsWith("F"))System.out.printf("%.1f°F=%.2f°C%n",v,f2c(v));
|
|
else System.out.println("未知单位:"+u);
|
|
}catch(Exception e){System.out.println("格式错误:"+s);}
|
|
}
|
|
public static void batch(String f){
|
|
try(Scanner sc=new Scanner(new File(f))){
|
|
System.out.println("批量转换:"+f);
|
|
int i=0;
|
|
while(sc.hasNextLine()){i++;System.out.print("第"+i+"行:");conv(sc.nextLine());}
|
|
System.out.println("转换完成");
|
|
}catch(FileNotFoundException e){System.out.println("文件不存在");}
|
|
}
|
|
public static void main(String[]a){
|
|
if(a.length==0){
|
|
Scanner sc=new Scanner(System.in);
|
|
System.out.print("输入温度(如36.6C):");
|
|
conv(sc.nextLine());
|
|
sc.close();
|
|
}else if(a.length==2)conv(a[0]+" "+a[1]);
|
|
else if(a.length==1)batch(a[0]);
|
|
else System.out.println("用法:\n1.java TemperatureConverter\n2.java TemperatureConverter 36.6 C\n3.java TemperatureConverter file.txt");
|
|
}
|
|
}
|