简体   繁体   中英

How should i format this loop so that it only prints the final iteration

I have a method which checks if user input (Scanner) is part of an ArrayList. Each iteration of the loop is being printed. I would like for 'Customer Found' to only be printed- if found. Likewise, the else function to only be printed once and not as many as the size of the array (3) in this case.

private static void checkCustomer() {
    String k;
    k = userOpt.nextLine();
    for (Customer c : customers) {
        for (int i = 0; i < c.getQtyCustomers(); i++) {
            c.getCustomerName();
        }
        if (c.getCustomerName().contains(k)) {
            System.out.println("Customer found.");
        }
        else {
            System.out.println(k + " is not a registered customer, try again.");
        }
    }
}

The Output:

Enter the full name of the customer.
Anna Smith
Anna Smith is not a registered customer, try again.
Customer found.
Anna Smith is not a registered customer, try again.

Thanks in advance.

I have achieved no duplication by removing the else{} statement but then I cant notify the user that they entered an invalid name - as far as i am aware.

You can exit from the method if you found a customer, as you know you will need to do no more searching. Additionally, we know that if you finish the loop without returning early, we have not found the customer, so we can print out a "not found" message.

private static void checkCustomer() {
    String k;
    k = userOpt.nextLine();
    for (Customer c : customers) {
        /* <- Also, do you need these three lines?
        for (int i = 0; i < c.getQtyCustomers(); i++) {
            c.getCustomerName();
        }
        */
        if (c.getCustomerName().contains(k)) {
            System.out.println("Customer found.");
            return;
        }
    }
    System.out.println(k + " is not a registered customer, try again.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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