我正在研究我正在製作的遊戲,當我遇到錯誤時。我的if/else if語句直接跳到else if語句,即使它不應該。簡單的Java如果/否則如果聲明不起作用
String neededCredits = "200";
if(Peeamnt.getText() == neededCredits) {
System.out.println("You can afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You have unlocked the Poop Button for 200 Pee Credits!",
"Toilet Master",
JOptionPane.WARNING_MESSAGE);
}
else if((!(Peeamnt.getText() == neededCredits))) {
System.out.println("You cannot afford this");
JOptionPane.showMessageDialog(BuyPoopButton,
"You do not have enough Credits to buy this!\n"
+ "To buy it, you need 200 Pee Credits!",
"Toilet Master",
JOptionPane.ERROR_MESSAGE);
}
即使Peeamnt的文本爲偶數200,代碼將跳轉到的else if語句,告訴我,我沒有200個小便學分。 (我製作的遊戲包含很多廁所幽默。)無論如何,如果任何人看到我在這個代碼中的錯誤,請讓我知道。讓我知道你是否需要更多的代碼。
部分。我猜.equals(){解決了我的問題。謝謝。 ;) – FreshCoffee
可能不需要兩次調用'getText'。如果'neededCredits.equals(Peeamnt.getText())'爲false,那麼'else'部分將自動發生。你不需要再把'neededCredits'測試放在那裏。如果'getText()'實際上做了類似於等待用戶鍵入內容的事情,那麼您發佈的代碼將等待兩次輸入,這可能不是您想要的。 – ajb