所以我试图用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 和 Customer 类已被调用。
最佳答案
问题出在你的循环中,你检查第一个元素,然后打印它或“循环突破”。您的其余项目永远不会被检查。
相反,您应该跟踪是否找到了对象。
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(" ");
}
}
关于java - 链表仅适用于第一个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50133388/