[英]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.