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;
}
You use a
break
statement within the loop. This causes the loop to exit.so try this code.
Well it makes sense, since if you succeed you return and if you don't, you break, so it breaks:
The
break;
statement is executed whenever the condition isn't met (otherwise you wouldreturn
before you reach it), which is why you always check only the first item.If you want to check all the items, simply remove the
break;
statement from your loop.As has been pointed in the comments, you have only two alternatives in the loop, both make the loop to finish (on
return
or onbreak
) Just take off thebreak;
statement or change it for acontinue;
.By the way, why don't you
select from User where role = 'recruiter'
only? This will make the roundtrip to the database server not to return all users, but only the ones that you are interested in.Your code and logic are wrong.
u
doesn't change during an iteration of thefor-each
loop, it changes after each iteration. Yourprintln
statements suggest that you believeu
is going to change during the first nestedif
statement. Since:and:
appear in the same
if
block, nested in thefor-each
loop:You also don't need to use a
break
orcontinue
statement. You don't need abreak
statement because you have areturn
statement. You don't need acontinue
statement because that's what a loop does.Note also that an
if
statement with no curly braces ({ ... }
) only executes the line directly below it. For instance:Your code should resemble:
If you want to have a
println
statement that outputs what the current username's index is, then don't use afor-each
use a regularfor
loop. For instance: