//用户信息类
public class User {
private String username;
private String password;
private String birthday;
private String hobby;
public User() {}
public User(String username,String password,String birthday,String hobby) {
this.username = username;
this.password = password;
this.birthday = birthday;
this.hobby = hobby;
}
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;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
import java.util.Scanner;
public class Test1 {
// 定义一个存储用户登录名和密码,长度为3的对象数组
private static User[] userArray = new User[3]; // 没讲过
private static int index = 0; // 没讲过
public static void main(String[] args) {
// 创建键盘录入对象
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("1.注册" + "\t" + "2.登录" + "\t" + "3.退出");
int select = sc.nextInt();
switch (select) {
case 1:
registe();
break;
case 2:
login();
break;
case 3:
System.out.println("感谢使用,再见");
System.exit(0);
default:
break;
}
}
}
// 注册方法
public static void registe() {
// 先验证用户是否已满
if (index >= userArray.length) {
System.out.println("用户已满,禁止注册");
return; // 不太明白为什么不能用else
}
Scanner sc = new Scanner(System.in);
System.out.println("请输入您的用户名:");
String userName = sc.nextLine();
System.out.println("请输入您的登录密码:");
String password = sc.nextLine();
System.out.println("请输入您的生日:");
String birthday = sc.nextLine();
System.out.println("请输入您的爱好(多个爱好中间用逗号隔开):");
String hobby = sc.nextLine();
// 将数据输入到数组
User user = new User(userName, password, birthday, hobby);
userArray[index] = user; // 不太明白
// 将索引增加1,以便下一次储存
index++; // 不太明白
System.out.println("注册成功");
}
// 登录方法
public static void login() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入您的用户名:");
String userName = sc.nextLine();
System.out.println("请输入您的密码");
String password = sc.nextLine();
// 使用登录名和密码进行验证
for (int x = 0; x < userArray.length; x++) {
if (userName.equals(userArray[x].getUsername()) && password.equals(userArray[x].getPassword())) {
System.out.println("登录成功,以下是您的个人信息");
System.out.println("用户名:" + userArray[x].getUsername() + "\t" + "密码:" + userArray[x].getPassword()
+ "\t" + "生日:" + userArray[x].getBirthday() + "\t" + "爱好" + userArray[x].getHobby());
return; //同上
}
}
System.out.println("用户名或密码错误!");
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b9dd1f9a3df422c8895896b42a4a3fe1.jpeg#pic_center)