【发布时间】:2015-07-14 00:41:35
【问题描述】:
我这里有一个代码应该将摄氏度转换为华氏度,反之亦然,然后询问用户是否要再次运行该程序。但是,用户只能输入一个范围为 -100 - 100 的数字。如果用户输入的数字大于或小于该范围,则必须要求用户输入一个新数字。我在程序结束时遇到问题,并要求用户在输入正确的数字后重新运行程序。有没有人有什么建议?谢谢!
import javax.swing.JOptionPane;
public class Temp3 {
public static void main(String[] args) {
// String sentence = "This is a Java program for converting
// temperatures.";
float option = JOptionPane.YES_OPTION;
while (option == JOptionPane.YES_OPTION) {
option = JOptionPane.showConfirmDialog(null, "Would you like to convert from Celsius to Fahrenheit?");
if (option == JOptionPane.YES_OPTION) {
c2f();
}
else if (option == JOptionPane.NO_OPTION) {
f2c();
}
else {
JOptionPane.showMessageDialog(null, "Goodbye");
System.exit(0);
}
option = JOptionPane.showConfirmDialog(null, "Would you like to run the program again?");
}// while loop
if (option == JOptionPane.NO_OPTION) {
JOptionPane.showMessageDialog(null, "Goodbye");
} // main method
}
private static void c2f() {
String celVal = JOptionPane.showInputDialog("Please enter degrees in Celsius. ");
float cel = Float.parseFloat(celVal);
while (cel <= 100 && cel >= -100) {
double holder = ((cel * 1.8) + 32);
JOptionPane.showMessageDialog(null, "The temperature in Fahrenheit is " + holder);
break;
}
while (cel > 100) {
String celVal2 = JOptionPane.showInputDialog("That number is too high. Please enter a number lower than 100 and try again.");
float cel2 = Float.parseFloat(celVal2);
while (cel2 <= 100 && cel2 >= -100){
JOptionPane.showMessageDialog(null, "The temperature in Fahrenheit is " + ((cel2 * 1.8) + 32));
cel2 = 101;
}
}
}
// cel to fah
private static void f2c() {
String fahVal = JOptionPane.showInputDialog(
"You are now converting from Fahrenheit to Celsius. Please enter degrees in Fahrenheit.");
float fah = Float.parseFloat(fahVal);
while (fah < 100 && fah >-100){
JOptionPane.showMessageDialog(null, "The temperature in Celcius is " + ((fah - 32) / 1.8));
break;
}
if (fah > 100) {
JOptionPane.showMessageDialog(null,
"That number is too high. Please enter a temperature less than 100 and try again.");
}
else if (fah < -100) {
JOptionPane.showMessageDialog(null,
"That number is too low. Please enter a temperature more than -100 and try again.");
}
} // fah to cel
【问题讨论】:
-
你的程序有什么问题?请提供有关预期和实际行为的更多详细信息。
-
如果你运行程序,它会询问你是否要将 cel 转换为 far,然后如果你输入一个范围内的数字,它会起作用,如果你输入一个大于 100 的数字,它会问你再试一次,如果您再试一次并输入范围内的数字,它将起作用。然后它应该询问用户是否要再次运行该程序,但是会出现输入框“数字太高,请尝试较低的数字”窗格。
-
您真的需要使用确认对话框吗?它可能会无限循环,因为 yes 会将摄氏度转换为华氏度,而 no 会将华氏度转换为摄氏度
标签: java loops while-loop