简体   繁体   中英

Why does my loop not end?

This Method tests if the accountnumber is in the given array

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;
}

Expected to return true or false but it seems to be a neverending loop which retirns nothing.

Try this

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; 
}

Much cleaner, less variables & makes it easy to detect the real problem in your code. (Could be something with the allAccounts array, or the accountNumber )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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