package chapter2; import java.util.Scanner; public class User { // 存储用户名和密码 // 两个数组前加上static属性,这样做是为了让本类都可以使用到这两个数组 static String[] usernames = new String[10]; static String[] passwords = new String[10]; static int count = 1; public static void main(String[] args) { // 假设系统中已经有一个用户 usernames[0] = "java"; passwords[0] = "123456"; while (true) { print(); Scanner input = new Scanner(System.in); System.out.println("请选择功能:"); int option = input.nextInt(); switch (option) { case 0: System.exit(0); case 1: login(); break; case 2: register(); break; case 3: show(); break; default: System.out.println("输入错误!"); break; } } } /* * 登录功能,键盘输入用户名与密码 * 使用for循环加if判断验证输入的用户名与密码是否正确 */ public static void login() { Scanner input = new Scanner(System.in); System.out.println("请输入用户名:"); String username = input.next(); System.out.println("请输入密码:"); String password = input.next(); for (int i = 0; i < count; i++) { if (username.equals(usernames[i]) && password.equals(passwords[i])) { System.out.println("登录成功!"); return; } } System.out.println("登录失败,请重新输入"); } /* * 注册功能 * 定义一个boolean变量,使用for循序判断用户是否存在 * 如果用户不存在,在数组中插入注册的账号密码时 * 可能会有数组长度不够的情况,所以需要使用到 * 增加数组的长度,这里调用增加数组长度的方法add()。 */ public static void register() { Scanner input = new Scanner(System.in); System.out.println("请输入用户名:"); String username = input.next(); System.out.println("请输入密码:"); String password = input.next(); boolean flag = true; for (int i = 0; i < count; i++) { if (username.equals(usernames[i])) { System.out.println("用户名已存在"); flag = false; } } if (flag) { if (count < usernames.length) { count++; usernames[count - 1] = username; passwords[count - 1] = password; System.out.println("注册成功!"); } else { System.out.println("数组空间不足!"); } } } /* * 查看功能 */ public static void show() { for (int i = 0; i < count; i++) { System.out.println("用户名:" + usernames[i] + ",密码:" + passwords[i]); } } /* * 打印功能菜单 */ public static void print() { System.out.println("-----------------用户管理系统-------------------"); System.out.println("1.登录功能"); System.out.println("2.注册功能"); System.out.println("3.查看"); System.out.println("0.退出"); System.out.println("-----------------用户管理系统-------------------"); } }