链接列表仅与第一个链表一起使用

时间:2018-05-02 11:17:49

标签: java

所以我试图在java中查看Linkedlist中的所有数据。 它们看起来像这样:

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

然后我尝试使用此

基于id查看客户
   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;           
   }

然后我把它作为输出:

Enter a customer ID: 101
101 Allen   10

但是,如果我尝试查看102或103它不起作用

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

可能是什么问题? Allen和Customers课程已经被调用。

2 个答案:

答案 0 :(得分:2)

问题出在你的循环中,你检查第一个元素,然后打印它或`循环中断。其他物品永远不会被检查。

相反,你应该跟踪是否找到了一个物体。

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

答案 1 :(得分:0)

你在for结尾处休息了一下,只处理了第一个客户。 循环后处理结果

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

或者

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

然后

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