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

时间:2016-04-25 05:02:51

标签: java for-loop break

我有这种方法在登录前检查用户的用户名和密码。现在我的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;
}

5 个答案:

答案 0 :(得分:3)

嗯,这是有道理的,因为如果你成功了,你就会回来,如果你不这样做,你就会破裂,所以它会破裂:

for (User u: list) {
    System.out.println("Before if user is: " + u);
    if (u.getRole().equalsIgnoreCase("recruiter")) {
        // code which returns at the end
        return u;
    }
    break;      
}

只要条件不满足就会执行break;语句(否则在到达之前你会return),这就是你总是只检查第一项的原因。

如果要检查所有项目,只需从循环中删除break;语句。

答案 1 :(得分:3)

您在循环中使用break语句。这会导致循环退出。

答案 2 :(得分:1)

正如评论中所指出的,你在循环中只有两个选择,都可以完成循环(在returnbreak上)只需取消break;声明或更改为continue;

顺便问一下,为什么不只是select from User where role = 'recruiter'?这将使到数据库服务器的往返不会返回所有用户,而只返回您感兴趣的用户。

答案 3 :(得分:1)

您的代码和逻辑错误。在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;
}

您也不需要使用breakcontinue语句。您不需要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;
}

答案 4 :(得分:-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.