简体   繁体   中英

linked list always executing else statement

SoI have this code

private void customerRemove(){
   customers = new LinkedList <Customer>();
   customers.add(new Customer(1, "John", 20));
   customers.add(new Customer(2, "Mike", 21));
   customers.add(new Customer(3, "Harry", 22));
    System.out.println("\nRemoving a customer.");
   System.out.print("Enter a customer ID: ");
   int rmvId = In.nextInt();
   for (Customer rmvCustomer:customers){
        if(rmvCustomer.getID()== rmvId){
          customers.remove(rmvCustomer);
            System.out.println("Customer removed.");
            System.out.println(" ");
           break;             
    }
        else{
            System.out.println("That customer does not exist.\n");
            break;

        }
   }}

when I call this method. Always else statement is executed first why is this so and how can I solve this issue?

Your for loop is just iterating once. If customer is found, it will remove. If not found, it goes to else block and breaks the loop, thus it doesn't check further elements in the linked list.

   for (Customer rmvCustomer:customers){
        if(rmvCustomer.getID()== rmvId){
          customers.remove(rmvCustomer);
            System.out.println("Customer removed.");
            System.out.println(" ");
           return;             
       }
    }

    System.out.println("That customer does not exist.\n");
   }

There's no need of else part inside the for loop. In you case you're not waiting to iterate over all the Customers before showing on screen that Id is not found.

You can keep a boolean found variable that you'll set to true if Id matches. If no match is found, you print it out using the same found variable. Update your code like below:

private void customerRemove() {
    customers = new LinkedList<Customer>();
    customers.add(new Customer(1, "John", 20));
    customers.add(new Customer(2, "Mike", 21));
    customers.add(new Customer(3, "Harry", 22));
    System.out.println("\nRemoving a customer.");
    System.out.print("Enter a customer ID: ");
    int rmvId = In.nextInt();

    boolean found=false;
    for (Customer rmvCustomer : customers) {
        if (rmvCustomer.getID() == rmvId) {
            customers.remove(rmvCustomer);
            System.out.println("Customer removed.");
            System.out.println(" ")
            found=true;
            break;
        }
    }
    if(!found)
     System.out.println("That customer does not exist.\n");
}

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