[英]Loop doesn't end upon entering negative number until user finish entering all values.
I want the program to end as soon as user enters a value which is less than zero but this program keep asking all three value then exits. 我希望程序在用户输入小于零的值时立即结束,但是该程序会不断询问所有三个值,然后退出。
For instance, if I enter -3, 2, 1, The program doesn't display error after entering -3 for the first height, instead it takes all three values then display the "invalid height" message. 例如,如果我输入-3、2、1,则在为第一个高度输入-3之后,程序不会显示错误,而是会使用所有三个值,然后显示“无效高度”消息。
How do I make it program display error message of invalid height as soon as user enters a negative value? 用户输入负值后,如何使程序显示无效高度的错误消息?
//Program Asking user to input three different heights
HeightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower"));
HeightTwo = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of Second
Tower"));
HeightThree = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of Third Tower"));
If (centimeterHeightOne < 0 || centimeterHeightTwo < 0 || centimeterThree < 0)
{
JOptionPane.showMessageDialog(null, "Invalid height";
}
else
{
conditions...
}
Loop doesn't end upon entering negative number until user finish entering all values. 在用户输入完所有值之前,循环不会在输入负数时结束。
Because that's exactly what you're doing. 因为那正是您在做什么。 If you want to terminate after one negative value, put if
right after you ask for each input: 如果要在一个负值之后终止,请在要求每个输入后立即输入if
:
heightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower"));
if(heightOne < 0) {
displayError();
//return; ?
}
heightTwo = ...
if(heightTwo < 0) {
displayError();
}
...
Please follow Java Naming Conventions and change HeightOne
to heightOne
. 请遵循Java命名约定并将HeightOne
更改为heightOne
。
You need to include the check after every value, something like 您需要在每个值之后添加检查,例如
heightOne = Integer.parseInt(JOptionPane.showInputDialog("Enter Height of First Tower"));
if (heightOne < 0) {
JOptionPane.showMessageDialog(null, "Invalid height");
return;
}
The return
statement aborts the current method and returns, if the current method is main
, the program stops. return
语句中止当前方法并返回,如果当前方法是main
,则程序停止。 If you are not in the main
method, but you want to forcefully exit the program nevertheless, you can do this by calling System.exit()
. 如果您不在main
方法中,但是仍然要强制退出程序,则可以通过调用System.exit()
来执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.