3 回答
TA贡献1853条经验 获得超9个赞
实际上你把它弄得太复杂了。你真正的问题在于:
if ((H >= 122 && H <= 188) && (h.equals("N") || b.equals("N")))
OR 运算符应该是 AND 运算符。如果此人没有心脏问题,无论 的值是多少,您的测试都将始终成功b。这就是为什么即使更改值,输出也不会改变。
我认为像下面这样的简单解决方案已经足以实现您想要的目标:
// Please use sensible names for your variables, and no uppercase single letters
double height = Double.parseDouble(heightField.getText()); // This could throw a NumberFormatException, you probably want to catch it
String backIssues = backField.getText();
String heartIssues = heartField.getText();
// Drop your first if test, it is completely unnecessary there.
// If the person is between 122 and 188 cm, and has no heart issues and has no back issues: Hooray!
if (height >= 122 && height <= 188 && heartIssues.equalsIgnoreCase("N") && backIssues.equalsIgnoreCase("N")) {
output.setText("You are cleared to ride, have fun!");
} else { // In all other cases, not allowed to ride the coaster
output.setText("Sorry, its not safe for you to ride the coaster");
}
TA贡献1869条经验 获得超4个赞
你的错误在这一行:
if ((H >= 122 && H <= 188) && (h.equals("N") || b.equals("N"))) {
事实上,如果你的身高合适,即使你有另外两个问题之一,你也可以去坐过山车。如果您输入 h="N" 和 b="Y",则条件h.equals("N") || b.equals("N")
将为 true,因为 h="N"。最好的做法是将这一行替换为:
if ((H >= 122 && H <= 188) && (h.equals("N") && b.equals("N"))) {
你也可以简化你的代码,你放了太多的if...
TA贡献1828条经验 获得超6个赞
您有太多多余的 if/else 语句。您可以像这样简化您的代码:
//Heart or back problem, so no riding
if (h.equals("Y") || b.equals("Y")) {
output.setText("Sorry, its not safe for you to ride the coaster");
}
else { //health ok, check height
if (H >= 122 && H <= 188)
output.setText("You are cleared to ride, have fun!");
else
output.setText("You are outside the height requirements, you can't ride")
}
另请记住,如果用户输入的高度值不是数字,您将抛出异常。
添加回答
举报