0

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

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)方法不会传递元素,即使它已添加到列表中。请一些建议

4

1 回答 1

0

您的 delete 方法需要将要删除的用户对象作为参数传入。当前,您正在声明一个新用户对象,该对象不包含有关您要删除的用户的任何信息,除非您提示输入用户名。您应该将用户对象传递给 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");
}
于 2013-04-04T00:31:30.373 回答