我是Java新手。请在以下帮助我
当布尔值为false时,我需要打印“身份验证失败”。但是,即使身份验证成功,下面的代码也会显示“成功”和“失败”消息。 *
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
答案 0 :(得分:0)
从您显示的输出中看来,您在Account
中有多个accountArray
,并且正在发生的事情是数组中的一个帐户匹配,但最后一个不匹配。因此,当您遍历accountArray
时,它将根据该帐户设置result
。阵列中的一个帐户成功(您一次打印“身份验证成功”),而最后一个不匹配。在循环之后,您打印“验证失败”,因为最后的检查将result
设置为false。
打印“身份验证成功”后可能要放入break;
的内容-找到匹配的帐户后,您已经完成了操作,并且不想查看其中的任何以后的帐户。向量。但是,由于您从未说过自己实际上想做什么,所以很难说。
此外,循环中的else
子句是多余的-如果result
为false则它将运行,因此再次将其设置为false是没有意义的。如果accountArray为空,您的代码还将结果保留为true,并且不打印任何消息;可能明智也可能不明智。