Java链接列表查找框架

时间:2013-04-04 00:19:45

标签: java linked-list

我有两个JAVA类User和Users。用户是主类,它将列出链接列表中用户类的实例。用户应该能够添加和删除用户。我的cos没有删除。

import java.util.*;
public class Users {

// Main method
public static void main(String[] args) {
    new Users();
}
//attributes
private LinkedList<User> users = new LinkedList<User>();

//Constructors
public Users(){
    add();
    add(); 
}

//Methods

//adds a user to the list
private void add(){
    users.add(new User());
}
//deletes a user from the list
private void delete(){
    User user = user(readName());
    if (user != null)
        users.remove(user);
    else
        System.out.println("    No such user");
}
 //returns the user if the user exists in the list
private User user(String name){
    for (User user: users)
        if (user.matches(name)){
            return user;
        }
    return null;

}
private String readName(){
    System.out.print("  Names: ");
    return In.nextLine();
}

}


User class

public class User {

//Attributes
private String name;
private Users users;

//Constructors
public User(){
    this.name = readName();
}

//Methods
//checks if the parameter is equal to the name field
public boolean matches(String name){
    return this.name == name;
}
public void add(){
    System.out.print(" " + name);
}
public void delete(){

}
public String readName(){
    System.out.print("  Name: ");
    return In.nextLine();
}

}

在Users类中,user(String s)方法未传递元素,即使它已添加到列表中。 请一些建议

1 个答案:

答案 0 :(得分:0)

您的删除方法需要将要删除的用户对象作为参数传入。目前,您正在声明一个新的用户对象,该对象不包含您要删除的用户的任何信息,除非您提示输入用户的名称。您应该将用户对象传递给delete方法,使其看起来像这样。

//deletes a user from the list
private void delete(User user) {
    if (user != null) 
        users.remove(user);
    else
        System.out.println("     No such user");
}