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")
}
另請記住,如果用戶輸入的高度值不是數字,您將拋出異常。
添加回答
舉報