猿问

代码仅输出相同的内容,不会使用 .equals 来输出不同的内容

我正在为我所在的班级做一个项目,任务是制作一个需要Netbeans3 个输入的程序,

  1. 人的身高,

  2. 背部问题

  3. 心脏问题。

老师说这两题要用boolean。他希望我们用它来inputBack.equals("N")看看它是否等于N我得到的输入,无论如何,如果有人可以帮助我,我会将我的代码放在下面,那就太好了!

基本上,程序仅在我更改高度时输出不同,但我需要它在bh时显示其他内容Y

double H;


String b, h;

b = back.getText();

h = heart.getText();


H = Double.parseDouble(height.getText());


if (h.equals("Y") || b.equals("Y")) {

    output.setText("Sorry, its not safe for you to ride the coaster");

}


if ((H >= 122 && H <= 188) && (h.equals("N") || b.equals("N"))) {

    output.setText("You are cleared to ride, have fun!");

} else if (b.equals("Y") || h.equals("Y")) {

    output.setText("Sorry, its not safe for you to ride the coaster");

} else {

    output.setText("Sorry, its not safe for you to ride the coaster");

}


jeck猫
浏览 179回答 3
3回答

暮色呼如

实际上你把它弄得太复杂了。你真正的问题在于: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 lettersdouble height = Double.parseDouble(heightField.getText()); // This could throw a NumberFormatException, you probably want to catch itString 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")) {&nbsp; output.setText("You are cleared to ride, have fun!");} else { // In all other cases, not allowed to ride the coaster&nbsp; output.setText("Sorry, its not safe for you to ride the coaster");}

MMTTMM

你的错误在这一行:if&nbsp;((H&nbsp;>=&nbsp;122&nbsp;&&&nbsp;H&nbsp;<=&nbsp;188)&nbsp;&&&nbsp;(h.equals("N")&nbsp;||&nbsp;b.equals("N")))&nbsp;{事实上,如果你的身高合适,即使你有另外两个问题之一,你也可以去坐过山车。如果您输入 h="N" 和 b="Y",则条件h.equals("N") || b.equals("N")将为 true,因为 h="N"。最好的做法是将这一行替换为:if&nbsp;((H&nbsp;>=&nbsp;122&nbsp;&&&nbsp;H&nbsp;<=&nbsp;188)&nbsp;&&&nbsp;(h.equals("N")&nbsp;&&&nbsp;b.equals("N")))&nbsp;{你也可以简化你的代码,你放了太多的if...

30秒到达战场

您有太多多余的 if/else 语句。您可以像这样简化您的代码://Heart or back problem, so no ridingif (h.equals("Y") || b.equals("Y")) {&nbsp; &nbsp; output.setText("Sorry, its not safe for you to ride the coaster");}else {&nbsp; //health ok, check height&nbsp; if (H >= 122 && H <= 188)&nbsp; &nbsp; &nbsp; output.setText("You are cleared to ride, have fun!");&nbsp; else&nbsp; &nbsp; &nbsp; output.setText("You are outside the height requirements, you can't ride")}另请记住,如果用户输入的高度值不是数字,您将抛出异常。
随时随地看视频慕课网APP

相关分类

Java
我要回答