我是java新手,我读了几章。只是不知道如何在该程序中使用另一种方法将温度从 F 转换为 C,反之亦然 这是我现在的代码:
import java.io.*;
import javax.swing.JOptionPane;
public class Converter {
public static void main(String[] args) throws Exception{
String unit = JOptionPane.showInputDialog("Enter unit F or C: ");
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String temp1 = JOptionPane.showInputDialog("Enter the Temperature: ");
double temp = Double.valueOf(temp1).doubleValue();
if((unit.equals("F"))||(unit.equals("f"))){
double c= (temp - 32) / 1.8;
JOptionPane.showMessageDialog(null,c+" Celsius");
}
else if((unit.equals("C"))||(unit.equals("c"))){
double f=((9.0 / 5.0) * temp) + 32.0;
JOptionPane.showMessageDialog(null,f+" Fahrenheit");
}
}
}
最佳答案
您可以创建静态方法来从一个方法转换为另一个方法,例如
public static double fahrenheitToCelsius(double temp) {
return (temp - 32) / 1.8;
}
等等
旁注:您可以将 if 子句简化为 if(unit.equalsIgnoreCase("F"))
或更好的 if("F".equalsIgnoreCase(unit))
code>,因为它也可以处理 unit = null
。
关于java - 您将如何在此程序中添加另一个方法?转换温度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9768954/