小编典典

为什么我的for循环仅检查第一个元素?

java

我有这种方法,可以在登录前检查用户名和密码。现在,我的for循环仅检查第一个项目,它发现第u.getRole().equalsIgnoreCase("recruiter")一个项目不满足第一个条件,因此与其去检查第二个项目,它只是中断并返回null。

为什么会这样?

这是我的方法:

public User check(String userName, String password) throws AdException {

    try {
        begin();
        Query q = getSession().createQuery("from User");
        ArrayList<User> list = (ArrayList<User>) q.list();
        System.out.println("recruiterList is: " + list);

        for (User u: list) {
            System.out.println("Before if user is: " + u);

            if (u.getRole().equalsIgnoreCase("recruiter")) {
                System.out.println("userName 1 is :" + u.getUserName());

                if (u.getUserName().equalsIgnoreCase(userName) && u.getPassword().equalsIgnoreCase(password))
                    System.out.println("After if recruiter is: " + u);
                System.out.println("userName 2 is :" + u.getUserName());

                return u;
            }
            break;      
        }


    } catch (HibernateException e) {
        rollback();
        throw new AdException("Unfound " + userName, e);
    }

    return null;
}

阅读 279

收藏
2020-12-03

共1个答案

小编典典

for (User u: list) {
    if (u.getRole().equalsIgnoreCase("recruiter")) {

  //sysout

 if (u.getUserName().equalsIgnoreCase(userName) && u.getPassword().equalsIgnoreCase(password))
          //2 sysout
        return u;
     }
     break;      //here break statement will exit your loop just after first Iteration.
 }

因此,请尝试此代码。

 for (User u: list) {
    if (u.getRole().equalsIgnoreCase("recruiter")) {

  //sysout

 if (u.getUserName().equalsIgnoreCase(userName) && u.getPassword().equalsIgnoreCase(password)){
          //2 sysout
        return u;
    } else{
               //your code if password doesnot matched
       }
      // continue even if more than one recruiter type User Object are in Database.
     }else{
               //your code if user Role doesnot matched
       }

 }   //loop will check all element present in that array. and if it's ROLE is  matched like "Recuriter" then it will check user and password.
2020-12-03