public static void main(String[] args) {
//PROBLEM: -300 pops up before program shuts down
// Variables
double celsiusCalculation = 0;
String fahrenheitInput = "";
while (!(fahrenheitInput.equals("-300"))) {
fahrenheitInput = JOptionPane.showInputDialog(null,
"Enter a number (in Fahrenheit) to convert to Celsius:");
double fahrenheit = Double.parseDouble(fahrenheitInput);
celsiusCalculation = (fahrenheit - 32) * 5 / 9;
celsiusCalculation = (int)(celsiusCalculation * 10);
celsiusCalculation = celsiusCalculation / 10.0;
JOptionPane.showMessageDialog(null, celsiusCalculation);
}
}
嘿,伙计们。我的代码在这里有一点点问题。由于某种原因,它计算摄氏温度转换并给我答案,但是当我想输入“-300”(退出程序)时,它计算-300华氏度到摄氏度,然后退出。我怎么能绕过这个?
谢谢!
答案 0 :(得分:1)
有很多方法可以解决您的问题。 关键是在收到用户的输入后立即检查“-300”。
例如:
while (true) {
fahrenheitInput = JOptionPane.showInputDialog(null,
"Enter a number (in Fahrenheit) to convert to Celsius:");
if (fahrenheitInput.equals("-300"))
break;
double fahrenheit = Double.parseDouble(fahrenheitInput);
celsiusCalculation = (fahrenheit - 32) * 5 / 9;
celsiusCalculation = (int)(celsiusCalculation * 10);
celsiusCalculation = celsiusCalculation / 10.0;
JOptionPane.showMessageDialog(null, celsiusCalculation);
}
答案 1 :(得分:1)
只需添加一个if来验证它
public static void main(String[] args) {
//PROBLEM: -300 pops up before program shuts down
// Variables
double celsiusCalculation = 0;
String fahrenheitInput = "";
while (!(fahrenheitInput.equals("-300"))) {
fahrenheitInput = JOptionPane.showInputDialog(null,
"Enter a number (in Fahrenheit) to convert to Celsius:");
if(!"-300".equals(fahrenheitInput))
{
double fahrenheit = Double.parseDouble(fahrenheitInput);
celsiusCalculation = (fahrenheit - 32) * 5 / 9;
celsiusCalculation = (int)(celsiusCalculation * 10);
celsiusCalculation = celsiusCalculation / 10.0;
JOptionPane.showMessageDialog(null, celsiusCalculation);
}
}
}
-300也被计算出来,因为即使它将在循环结束时退出,你仍然会在结束前执行剩下的代码。
另一个选项包括使用break
:
while (!(fahrenheitInput.equals("-300"))) {
fahrenheitInput = JOptionPane.showInputDialog(null,
"Enter a number (in Fahrenheit) to convert to Celsius:");
if("-300".equals(fahrenheitInput))
break;
double fahrenheit = Double.parseDouble(fahrenheitInput);
celsiusCalculation = (fahrenheit - 32) * 5 / 9;
celsiusCalculation = (int)(celsiusCalculation * 10);
celsiusCalculation = celsiusCalculation / 10.0;
JOptionPane.showMessageDialog(null, celsiusCalculation);
}