用户管理系统:增加,删除,查找用户java代码
时间: 2024-01-09 22:05:46 浏览: 66
好的,下面是用户管理系统的Java代码示例:
User类:
```java
public class User {
private int id;
private String name;
private int age;
private String gender;
public User(int id, String name, int age, String gender) {
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
}
// getter and setter methods
}
```
UserDao接口:
```java
public interface UserDao {
void addUser(User user);
void deleteUser(int userId);
User findUserById(int userId);
User findUserByName(String userName);
}
```
UserDao的实现类UserDaoImpl:
```java
import java.util.HashMap;
import java.util.Map;
public class UserDaoImpl implements UserDao {
private Map<Integer, User> users = new HashMap<>();
private int id = 1;
@Override
public void addUser(User user) {
user.setId(id++);
users.put(user.getId(), user);
System.out.println("User added successfully!");
}
@Override
public void deleteUser(int userId) {
User user = users.remove(userId);
if (user != null) {
System.out.println("User deleted successfully!");
} else {
System.out.println("User not found!");
}
}
@Override
public User findUserById(int userId) {
User user = users.get(userId);
if (user != null) {
System.out.println("User found: " + user.getName());
} else {
System.out.println("User not found!");
}
return user;
}
@Override
public User findUserByName(String userName) {
for (User user : users.values()) {
if (user.getName().equals(userName)) {
System.out.println("User found: " + user.getName());
return user;
}
}
System.out.println("User not found!");
return null;
}
}
```
使用示例:
```java
public static void main(String[] args) {
UserDao userDao = new UserDaoImpl();
// add user
User user1 = new User(0, "Tom", 20, "Male");
userDao.addUser(user1);
// find user by id
userDao.findUserById(1);
// find user by name
userDao.findUserByName("Tom");
// delete user
userDao.deleteUser(1);
}
```
输出:
```
User added successfully!
User found: Tom
User found: Tom
User deleted successfully!
```
阅读全文