繁体   English   中英

方法返回false,但条件匹配并且应该返回true

[英]Method is returning false but conditions match and should be returning true

我目前有一些User对象,它们的类型为enum enumUserType,但是其中之一具有LIBRARIAN的enumUserType。 图书馆员的用户需要具有特殊权限,在这种情况下,它将具有可以访问的其他菜单。

我尝试执行的操作将遍历用户的数组列表,并且如果该用户的用户类型为图书管理员,则返回true,否则返回false。

经过一些测试,似乎即使我的一个对象只是图书馆员,整个方法也将返回true。 然后,我无法引导不同的用户类型进入不同的菜单路径。 我的第一个对象不是图书馆员,而第二个对象是图书馆员。

public boolean verifyLibrarian() {
    for (User s : users) {
    //if just one of my objects is librarian it will return true.
        if (s.getUserType() == User.enumUserType.LIBRARIAN) {
            return true;
         }
        else
        {
            return false;
        }
     }
       throw new IllegalArgumentException("Username or password is 
       incorrect");

}

这也是我的while循环:

while(exit == 0)
    {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your user name");
        String userName = scanner.nextLine();

        System.out.println("Enter your password name");
        String passWord = scanner.nextLine();


         if (library.verifyLogin(userName, passWord)== true && library.verifyLibrarian() != true)
            {
                this.currentLoginUser = userName;
                mainMenuAfterLogin();
            }
   //because my method is returning true, even logged in non librarians 
       //will get lead down to this menu
         else if(library.verifyLogin(userName, passWord) == true && 
         library.verifyLibrarian() == true)
         {
                this.currentLoginUser = userName;
                librarianMenuEditBook();

         }
    }

如果您需要更多信息,请与我们联系。 谢谢您的帮助。

您需要将return false放入循环之外,以在返回false之前检查每个用户

for (User s : users) {
//if just one of my objects is librarian it will return true.
    if (s.getUserType() == User.enumUserType.LIBRARIAN) {
        return true;
     }    
}
return false;

或使用anyMatch

return users.stream().anyMatch(s -> s.getUserType() == User.enumUserType.LIBRARIAN);

如果您的意图是在没有找到用户的情况下真正引发异常(当前在您的代码中无法访问),则抛出该异常而不是返回

public boolean verifyLibrarian() {
    for (User s : users) {
    //if just one of my objects is librarian it will return true.
        if (s.getUserType() == User.enumUserType.LIBRARIAN) {
            return true;
        }    
    }
    throw new IllegalArgumentException("Username or password is incorrect");
}

或在流中

users.stream()
      .filter(s -> s.getUserType() == User.enumUserType.LIBRARIAN)
      .findAny()
      .orElseThrow(() -> new IllegalArgumentException("Username or password is incorrect"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM