Why does my for loop check only the first element?

前端 未结 5 1272
心在旅途
心在旅途 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:27

    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.
    

提交回复
热议问题