亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

代碼僅輸出相同的內容,不會使用 .equals 來輸出不同的內容

代碼僅輸出相同的內容,不會使用 .equals 來輸出不同的內容

jeck貓 2023-08-23 14:35:55
我正在為我所在的班級做一個項目,任務是制作一個需要Netbeans3 個輸入的程序,人的身高,背部問題心臟問題。老師說這兩題要用boolean。他希望我們用它來inputBack.equals("N")看看它是否等于N我得到的輸入,無論如何,如果有人可以幫助我,我會將我的代碼放在下面,那就太好了!基本上,程序僅在我更改高度時輸出不同,但我需要它在b或h時顯示其他內容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");}
查看完整描述

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");

}


查看完整回答
反對 回復 2023-08-23
?
MMTTMM

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...


查看完整回答
反對 回復 2023-08-23
?
30秒到達戰場

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")

}

另請記住,如果用戶輸入的高度值不是數字,您將拋出異常。


查看完整回答
反對 回復 2023-08-23
  • 3 回答
  • 0 關注
  • 220 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號