如何检查布尔值是否为false

问题描述 投票:0回答:1

我是java新手..请帮我以下

当布尔值为false时,我需要打印“Authentication failed”。但是下面的代码显示成功和失败的消息,即使身份验证成功。 *

switch(choice){
            case 1:
                System.out.println("Enter the username");
                String name = scan.nextLine();
                System.out.println("Enter the password");
                String password = scan.nextLine();
                Boolean result = true;
              for(Account a :accountArray )
              {
                     result = a.authentication(name, password);
                    if(result)
                    {
                        System.out.println("Authentication successful");
                    }
                    else
                    {
                        result=false;
                    }


                }
               if(!result)
              {
                  System.out.println("Authentication failed");
              }

              break;

*

Current Output:
Enter the username
vicky
Enter the password
vicky123
Authentication successful
Authentication failed
boolean-operations
1个回答
0
投票

从您显示的输出看起来,您在Account中有多个accountArray,而且发生的事情是阵列中的一个帐户匹配,但最后一个不匹配。因此当你循环accountArray时,它根据该帐户设置result。阵列中的一个帐户成功(您打印“身份验证成功”一次),最后一个帐户不匹配。在循环之后,您打印“认证失败”,因为最后一次检查将result设置为false。

可能你希望它在打印“身份验证成功”后放置break; - 一旦找到匹配的帐户,你就完成了,并且不想查看向量中的任何后续帐户。但是,由于你从未说过你实际上想要做什么,所以很难说。

此外,循环中的else子句是多余的 - 如果result为false则运行,因此将其设置为false是没有意义的。如果accountArray为空,您的代码也会将结果保留为true,并且不打印任何消息;这可能是也可能不是明智的。

© www.soinside.com 2019 - 2024. All rights reserved.