将上述思路用基础的java代码写出来
时间: 2024-03-13 16:42:23 浏览: 64
好的,我来写一下基础的 Java 代码,实现上述思路:
1. User 类:
```
public class User {
private String username; // 用户名
private String password; // 密码
private String birthday; // 生日
public User(String username, String password, String birthday) {
this.username = username;
this.password = password;
this.birthday = birthday;
}
// getter 和 setter 方法
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
```
2. IUserDao 接口:
```
public interface IUserDao {
// 添加用户(注册功能)
public boolean addUser(User user);
// 查找用户(登录功能)
public User findUser(String username, String password);
// 修改用户(重置密码)
public boolean updateUser(String username, String password);
}
```
3. UserDaoImpl 实现类:
```
import java.util.ArrayList;
import java.util.List;
public class UserDaoImpl implements IUserDao {
private List<User> userList; // 用户列表
public UserDaoImpl() {
userList = new ArrayList<User>();
}
// 添加用户
public boolean addUser(User user) {
if (userList.contains(user)) {
return false;
}
userList.add(user);
return true;
}
// 查找用户
public User findUser(String username, String password) {
for (User u : userList) {
if (u.getUsername().equals(username) && u.getPassword().equals(password)) {
return u;
}
}
return null;
}
// 修改用户
public boolean updateUser(String username, String password) {
for (User u : userList) {
if (u.getUsername().equals(username)) {
u.setPassword(password);
return true;
}
}
return false;
}
}
```
4. TestUser 测试类:
```
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TestUser {
public static void main(String[] args) {
IUserDao userDao = new UserDaoImpl(); // 创建 UserDaoImpl 实例
// 添加3个用户信息
userDao.addUser(new User("user1", "password1", "1990-01-01"));
userDao.addUser(new User("user2", "password2", "1991-02-02"));
userDao.addUser(new User("user3", "password3", "1992-03-03"));
// 使用增强型 for 循环遍历 userList
List<User> userList = new ArrayList<User>();
userList = userDao.getUserList();
System.out.println("使用增强型 for 循环遍历 userList:");
for (User u : userList) {
System.out.println(u.getUsername() + " " + u.getPassword() + " " + u.getBirthday());
}
// 使用迭代器遍历 userList
Iterator<User> it = userList.iterator();
System.out.println("使用迭代器遍历 userList:");
while (it.hasNext()) {
User u = it.next();
System.out.println(u.getUsername() + " " + u.getPassword() + " " + u.getBirthday());
}
}
}
```
以上代码实现了基本的用户信息操作功能,包括添加用户、查找用户和修改用户,同时也包括了遍历 userList 的两种方式。
阅读全文