userZZZ userZZZ - 7 months ago 11
Java Question

Why my for loop checks only the first element?

I have this method that checks the username and password of a user before login. Now my for loop checks only the first item, it finds that the first condition,

u.getRole().equalsIgnoreCase("recruiter")
is not satisfied for the first item, so instead of going and checking the second item it just breaks and returns null.

Why does this happen?

Here is my method:

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;

}

Answer
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.
 }

so try this code.

 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.