package MONA.demo03_练习题;
import java.util.ArrayList;
import java.util.Scanner;
/**
* 模拟登陆注册
*/
public class Demo02 {
//加大sc的作用域
static Scanner sc = new Scanner(System.in);
//存储用户信息的集合
static ArrayList<User> users = new ArrayList();
public static void main(String[] args) {
ArrayList users = new ArrayList();
while (true) {
System.out.println("(1).注册 (2).登陆 (3).退出: (4).查看所有用户");
System.out.println("请输入:");
int input = sc.nextInt();
switch (input) {
case 1:
registerUser();
break;
case 2:
login();
break;
case 3:
System.out.println("欢迎下次使用!");
return;
case 4:
//直接调用System.out.println(users) user.toString()
System.out.println(users);
break;
}
}
}
/**
* 注册用户
*/
public static void registerUser() {
System.out.println("请输入用户名");
String username = sc.next();
String regex = "[0-9a-zA-Z]{6,16}";
if(!username.matches(regex)){
System.out.println("用户名格式不正确");
return;
}
System.out.println("请输入密码(密码长度为6~12)");//6~12
String password = sc.next();
//将输入的信息封装到User对象中
User user = new User(username, password);
//将封装后的user对象添加到集合中
users.add(user);
System.out.println("注册成功");
}
//登陆的方法
public static void login() {
System.out.println("请输入用户名");
String username = sc.next();
System.out.println("请输入密码");
String password = sc.next();
for (User user : users) {
if(user.getUsername().equals(username) && user.getPassword().equals(password)){
System.out.println("登陆成功");
return;
}
}
System.out.println("登陆失败");
}
static class User {
private String username;
private String password;
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 User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
}
案例之模拟用户登录注册
最新推荐文章于 2023-10-09 09:49:53 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)