简体   繁体   中英

Linked List only working with 1st linked list

So I am trying to view all data in the Linkedlist in java. They Look like this:

private List <Customer> customers;
public databse(){
customers.add(new Customer(101, "Allen", 10))
customers.add (new Customer(102, "John", 15))
customers.add (new Customer(103, "Lucy", 23))
}

Then i am trying to view the customer based on th id by using this

   private void customer(){
   System.out.println(" ");
   System.out.print("Enter a customer ID: ");
   int id = In.nextInt();
   for(Customer customer:customers )
   {
        if(customer.getID() == id){
            System.out.println(customer.toString());
            System.out.println(" ");
           // break;
          }
          else 
        {System.out.println("That customer does not exist.");
        System.out.println(" ");

        }
        System.out.println(" ");
     break;           
   }

Then i get this as an output:

Enter a customer ID: 101
101 Allen   10

However, if I try to view 102 or 103 it doesn't work

Enter a customer ID: 102 
That customer does not exist.

What might be the problem? Allen and Customers classes are already called.

The problem is in your loop where you check the first element and then either print it or `breakout of the loop. The rest of your items are never checked.

Instead you should keep track of if an object was found or not.

private void customer(){
    System.out.println(" ");
    System.out.print("Enter a customer ID: ");
    int id = In.nextInt();
    boolean found = false;
    for(Customer customer:customers ) {
        if(customer.getID() == id){
            System.out.println(customer.toString());
            System.out.println(" ");
            found = true;
            break;
        }
    }
    if (!found) {
        System.out.println("That customer does not exist.");
        System.out.println(" ");
    }
}

You did a break at the end of the for, handling only the first customer. Handle the result after the loop.

Optional<Customer> foundCustomer = Optional.empty();
for (Customer customer : customers) {
    if (customer.getID() == id) {
        foundCustomer = Optional.of(customer);
        break;
    }
}

Or

Optional<Customer> foundCustomer = customers.stream().findAny(c -> c.getID() == id);

and then

if (foundCustomer.isPresent()) {
    System.out.println(foundCustomer.get());
} else {
    System.out.println("That customer does not exist.");
}

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