Why does my for loop check only the first element?

前端 未结 5 1264
心在旅途
心在旅途 2021-01-29 07:36

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()

5条回答
  •  鱼传尺愫
    2021-01-29 08:13

    Well it makes sense, since if you succeed you return and if you don't, you break, so it breaks:

    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;      
    }
    

    The break; statement is executed whenever the condition isn't met (otherwise you would return 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.

提交回复
热议问题