您的代碼和邏輯錯誤。 u
在for-each
循環的迭代期間不會更改,它在每次迭代後都會更改。您的println
聲明表明您認爲u
將在第一個嵌套if
聲明期間發生變化。因爲:
System.out.println("userName 1 is :" + u.getUserName());
和:
System.out.println("userName 2 is :" + u.getUserName());
出現在同一if
塊,嵌套在for-each
循環:
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
或continue
聲明。您不需要break
聲明,因爲您有一個return
聲明。您不需要continue
聲明,因爲這是一個循環。
還要注意,沒有大括號的if
語句({ ... }
)僅執行直接在它下面的行。例如:
if (u.getUserName().equalsIgnoreCase(userName) && u.getPassword().equalsIgnoreCase(password))
System.out.println("After if recruiter is: " + u);
您的代碼應類似於:
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;
}
}
}
} catch (HibernateException e) {
rollback();
throw new AdException("Unfound " + userName, e);
}
return null;
}
如果你想有一個println
聲明輸出當前用戶名的指標是什麼,那麼就不要使用for-each
使用經常的for
循環。例如:
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 (int i = 0; i < list.length; i++) {
System.out.println("Before if user is: " + u);
if (u.getRole().equalsIgnoreCase("recruiter")) {
System.out.println("userName " + (i + 1) + " is :" + u.getUserName());
if (u.getUserName().equalsIgnoreCase(userName) && u.getPassword().equalsIgnoreCase(password)) {
System.out.println("After if recruiter is: " + u);
return u;
}
}
}
} catch (HibernateException e) {
rollback();
throw new AdException("Unfound " + userName, e);
}
return null;
}
你有一個'return'語句;你的'if'必須評估爲'true'(或你'break')。 –