运用数组存放用户名和密码,数组下标一一对应,静态数组定义在类里面使外部函数能直接调用。
import java.util.Scanner;
public class ManageSystem {
static Scanner scan = new Scanner(System.in);
static String[] userNames = new String[10];
static String[] passwords = new String[10];
static int sum = 0;//用户数量
public static void main(String[] args) {
int i = 4;
do {
if (i == 4) {
System.out.println("------ 黑马管理系统 ------");
System.out.println("1.登录功能(login)");
System.out.println("2.注册功能(register)");
System.out.println("3.查看(show)");
System.out.println("0.退出(exit)");
System.out.println("------ 黑马管理系统 ------");
System.out.print("请选择功能:");
i = scan.nextInt();
} else if (i == 1) {
if (loginIn()) {
System.out.println("登陆成功!");
} else {
System.out.println("登陆失败超过三次,已退出登陆页面!");
}
i = 4;
} else if (i == 2) {
if (!register()) {
i = 2;
} else i = 4;
} else if (i == 3) {
System.out.println("系统中存在的用户名有:");
showData();
i = 4;
} else i = 4;
} while (i != 0);
}
public static Boolean loginIn() {//登录函数
for (int chance = 0; chance < 3; chance++) {//三次机会,都不成功退出登陆界面
System.out.print("请输入登陆用户名:");
String userName = scan.next();
System.out.print("请输入密码:");
String password = scan.next();
int j = findUserName(userName);
if (passwords[j - 1].equals(password)) {
return true;
} else {
System.out.println("密码错误。");
}
}
return false;
}
public static boolean register() { //注册
String password = null;
for (int j = 0; j == 0; ) {
System.out.print("请输入注册用户名:");
String userName = scan.next();
if (userName != null) {//判断用户名是否重复
if (findUserName(userName) == 0) {
System.out.print("请输入密码:");
password = scan.next();
j++;
} else {
System.out.println("用户名重复。");
return false;
}
}
userNames[sum] = userName;
passwords[sum] = password;
System.out.println("注册成功");
sum++;
}
return true;
}
public static void showData() {//选项三 展示所有数据
for (int j = 0; j < sum; j++) {
System.out.println((j + 1) + ". 用户名:" + userNames[j] + " 密码:" + passwords[j]);
}
}
public static int findUserName(String u) {//寻找用户名(登录,注册)
for (int j = 0; j < sum; j++) {
if (userNames[j].equals(u)) {
return j + 1;
}
}
return 0;
}
}