繁体   English   中英

为什么我的循环没有结束?

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM