在循环中比较ArrayList的元素会产生意外结果吗?

时间:2018-09-06 12:34:44

标签: java arraylist foreach java.util.scanner

以下代码仅检查ArrayList中的第一项。当我键入位于ArrayList中但不在第一位置的项目时,收到错误消息,显示为“请输入有效名称”

我该如何解决?谢谢!

这是我的代码:

   private ArrayList<Account> accounts = new ArrayList<>();

   for(Account a : accounts)
    {
        while(true)
        {
            System.out.printf("Customer name: ");
            String customerName = scanner.next();

            if(customerName.equals(a.getName()))
            {
                System.out.println("You entered " + a.getName());
                break;
            }
            else
            {
                System.out.println("Please enter a valid name");
            }
        }
    }   

4 个答案:

答案 0 :(得分:1)

内部循环可以做到这一点:

while(true) {

在这里没有目的。它只是保持内部内部循环,因此始终与同一个a帐户进行比较!

基本上,您必须交换两个循环!

答案 1 :(得分:1)

问题在于无限的while循环。

while(true)

此循环仅在customerName == firstElement.Name时中断,否则为无限循环。相反,我认为您想尝试的是将while循环移到for循环之外。因此代码看起来像这样。

    private ArrayList<Account> accounts = new ArrayList<>();

    while(true)
    {
        System.out.printf("Customer name: ");
        String customerName = scanner.next();
        for(Account a : accounts){

           if(customerName.equals(a.getName())){
                 System.out.println("You entered " + a.getName());
                 break;
           }else{
            System.out.println("Please enter a valid name");
           }
        }
    }

答案 2 :(得分:1)

您必须从此休息一下。在列表上进行迭代时,您必须考虑逻辑。它可以像这样的代码;

ArrayList<Account> accounts = new ArrayList<>();
boolean isMatched = false;

while (true) {
    for (Account account : accounts) {
        System.out.printf("Customer name: ");
        String customerName = scanner.next();
        if (customerName.equals(account.getName())) {
            isMatched = true;
            break;
        }
    }
    if (isMatched) {
        System.out.println("You entered " + account.getName());
        break;
    }
    System.out.println("Please enter a valid name");
}

PS: boolean的值,用于找到要在循环结束时结束的客户名称。

答案 3 :(得分:0)

您遇到的问题是因为您一直只在检查第一个元素。输入第一个元素后(并中断while(1)循环),您将转到第二个元素。

想象一下您的arrayList中有

"hello", "bye"

您将一直处于循环中,直到向第一个元素(“ hello”)发短信为止。

解决方案:

 while(true)
         {
             System.out.printf("Customer name: ");
             String customerName = scanner.next();
             if (accounts.contains(customerName)){
                 System.out.println("You entered " + customerName);
                 break;
             }
             else{
                 System.out.println("Please enter a valid name");
             }
         }
相关问题