Samrat
Samrat

Reputation: 476

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?

Upvotes: 0

Views: 49

Answers (2)

Shanu Gupta
Shanu Gupta

Reputation: 3807

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");
}

Upvotes: 0

Sandesh Gupta
Sandesh Gupta

Reputation: 1195

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");
   }

Upvotes: 5

Related Questions