[英]Why does my loop not end?
此方法測試帳號是否在給定數組中
public boolean containsAccount(int accountNumber) {
int i;
boolean ausgabe = false;
for (i = 0; i < allAccounts.length; i++) {
if (allAccounts[i].getAccountNumber() == accountNumber) {
ausgabe = true;
}
else if (i == length() - 1) {
ausgabe = false;
}
}
return ausgabe;
}
預期返回 true 或 false,但它似乎是一個永無止境的循環,什么都不返回。
嘗試這個
public boolean containsAccount(int accountNumber) {
for (int i = 0; i < allAccounts.length; i++) {
if (allAccounts[i].getAccountNumber() == accountNumber) {
return true;
}
}
// If the execution flow reaches this line, then that
// means that the account 'id' does not exist in the array
return false;
}
更干凈,更少的變量,並且可以輕松檢測代碼中的真正問題。 (可能是allAccounts
數組或accountNumber
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.