使用搜索数组保持新用户

时间:2012-04-24 15:20:26

标签: java android arrays

我正在尝试搜索数组,如果两个字符串匹配则返回true,否则为false,首先我要搜索以查看该帐户是否已存在,如果是,则搜索Code如果两个exsis然后返回true

public boolean searchArray(String account, String code) {    
    for (Accounts a : bAccounts) {
        if (a.getAccount().equals(account)) {
            for (Accounts c : bAccounts) {
                if (c.getCode().equals(Code))
                    return true;
                }
            }
        }

    return false;
}

认为我在这种搜索方法中有点迷失,有人可以帮我解决这个问题,谢谢。这一切都很好,但似乎没有返回任何东西。我在我的Accounts类中获取了一些方法,它们为Account和Sort提供了get和set方法。

2 个答案:

答案 0 :(得分:1)

public boolean searchArray(String account, String code) {    
    for (Accounts a : bAccounts) {
        if (a.getAccount().equals(account)
                  && a.getCode().equals(code)) {                
            return true;                    
        }
    }

    return false;
}

应该删除内部。

答案 1 :(得分:0)

您没有提及是否接受帐户和代码参数的空值。

如果可以/希望比较空值,我建议这样做:

public boolean searchArray(String account, String code) {

    for (Account a : accounts) {
        if (account == null) {
            if (code == null) {
                if ((a.getAccount() == null) && (a.getCode() == null)) {
                    return true;
                }
            } else {
                if ((a.getAccount() == null) && code.equals(a.getCode())) {
                    return true;
                }
            }
        } else {
            if (code == null) {
                if (account.equals(a.getAccount()) && (a.getCode() == null)) {
                    return true;
                }
            } else {
                if (account.equals(a.getAccount()) && code.equals(a.getCode())) {
                    return true;
                }
            }
        }
    }

    return false;
}

如果您不考虑帐户和代码参数的空值,我建议:

public boolean searchArray(String account, String code) {
    // if you won't consider nulls then there's no need to search
    // when at least one of them is null
    if ((account == null) || (code == null)) {
        return false;
    }

    for (Account a : accounts) {
        if (account.equals(a.getAccount()) && code.equals(a.getCode())) {
            return true;
        }
    }

    return false;
}

希望它可以帮到你