Java for 循环与 if 语句仅迭代一次

标签 java for-loop linked-list

我有一个我想要制作的员工系统登录版本,我有一个 for 循环,它应该遍历整个帐户列表,然后查看员工的姓名是否与列表中的一个匹配,然后 if 语句继续,询问进一步的问题等...它似乎只迭代一次,然后停止,因为它只会找到第一个用户并告诉我其他帐户不存在,即使它们存在!我究竟做错了什么?另外,我的列表包含从 Account 继承的员工和经理,if 语句使用 Account 中的 getName 来比较它是否等于用户输入。抱歉,如果这太愚蠢/糟糕了!谢谢。

List <Account> Accounts = new LinkedList<Account>();   

这是我填充我的帐户的地方,主方法调用它,并且调用 list() ,其中包含有问题的循环

public void add() {
    Employee Geoff = new Employee("Geoff", "password1");
    Manager Bob = new Manager("Bob", "password2");
    Employee John = new Employee("John", "password3");

    Accounts.add(Geoff);
    Accounts.add(Bob);
    Accounts.add(John);
    list();

    }

问题:

System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();

for (Account a : Accounts) { 
        System.out.println(a);
        if (a.getname().equals(empName)) {

            System.out.println("\nPlease enter your passcode: ");

            String code = Scan.nextLine();

                if (a.check(code) == true) {
                    System.out.println("logged in");
                }
            }
        System.out.println("Employee does not exist!");
        login();

    }

我正在 for 循环中执行打印语句来查看它找到了什么,不幸的是它只是第一个帐户

编辑:我在这里包含了更多代码,在最初的 if 语句之后我想检查用户输入的代码是否也正确。

最佳答案

see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!!

如果它适用于一名员工并告诉其他员工不存在,那么您的 for 循环不会不会迭代一次。

您得到的输出与代码完全相同。您获取用户名一次,然后尝试将相同的名称与列表中的每个员工相匹配。如果姓名相同,您将要求输入密码,否则您会打印出该员工不存在。一切都和代码中一样正确。您应该在您的问题中添加预期的行为,以便我或其他人可以修复您的代码而无需猜测您的方法的目的。

这是其中一个猜测:

System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) { 
        System.out.println(a);
        if (a.getname().equals(empName)) {
            System.out.println("\nPlease enter your passcode: ");
            String code = Scan.nextLine();
                if (a.check(code) == true) {
                    System.out.println("logged in");
                    userFound = true;
                    break;
                }
            }
    }

if(userFound) {
    login();
} else {
    System.out.println("User not found.");
}

关于Java for 循环与 if 语句仅迭代一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28841729/

相关文章:

node.js - Node js等待函数返回以继续for循环

java - 使用链接整数节点的插入排序

c - 链表 : Should the type of pointer "next" and the name of struct be same?

java - ListenableFuture回调执行顺序

java - java中如何在函数返回之前等待某个回调方法被调用?

java - 2 个随机数组的交集 - Java

c - 链表C插入函数

java - maven-surefire-report-plugin 2.8 错误 : org. apache.maven.doxia.siterenderer.sink.SiteRendererSink.unknown

Java 负整数转十六进制并返回失败

scala - Scala: `for`模式匹配“无”情况下的奇怪行为