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.
CodePudding user response:
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.");
}