Java Library Management System with Login, Registration and Password Recovery
First, define the User entity class to store user account information, including username, password, ID card number and phone number:
public class User {
private String username;
private String password;
private String idCardNumber;
private String phoneNumber;
public User() {}
public User(String username, String password, String idCardNumber, String phoneNumber) {
this.username = username;
this.password = password;
this.idCardNumber = idCardNumber;
this.phoneNumber = phoneNumber;
}
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 getIdCardNumber() { return idCardNumber; }
public void setIdCardNumber(String idCardNumber) { this.idCardNumber = idCardNumber; }
public String getPhoneNumber() { return phoneNumber; }
public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }
}
Next, define the Book entity class to store book core information:
public class Book {
private int bookId;
private String bookTitle;
private String author;
private int price;
public Book() {}
public Book(int bookId, String bookTitle, String author, int price) {
this.bookId = bookId;
this.bookTitle = bookTitle;
this.author = author;
this.price = price;
}
public int getBookId() { return bookId; }
public void setBookId(int bookId) { this.bookId = bookId; }
public String getBookTitle() { return bookTitle; }
public void setBookTitle(String bookTitle) { this.bookTitle = bookTitle; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
public int getPrice() { return price; }
public void setPrice(int price) { this.price = price; }
}
The main auhtentication entry class provides the initial menu with three core functions: login, registrasion and password recovery, with complete input validatino rules:
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class LibraryAuthApp {
private static final String OPTION_LOGIN = "1";
private static final String OPTION_REGISTER = "2";
private static final String OPTION_RECOVER_PASSWORD = "3";
private static ArrayList<User> userList = new ArrayList<>();
// Pre-populate test user data
static {
userList.add(new User("zhangsan", "123456", "110101199001011234", "13800138000"));
userList.add(new User("lisi", "654321", "31010119950505123X", "13900139000"));
}
public static void main(String[] args) {
showMainMenu(userList);
}
public static void showMainMenu(ArrayList<User> users) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("===== Library Management System =====");
System.out.println("Please select an option:");
System.out.println("1. Login 2. Register 3. Forgot Password");
System.out.println("======================================");
String selection = scanner.next();
switch (selection) {
case OPTION_LOGIN -> {
System.out.println("----- Login Page -----");
boolean loginSuccess = processLogin(users);
if (loginSuccess) {
BookManagementSystem bookManager = new BookManagementSystem();
bookManager.startManagementInterface();
System.exit(0);
}
}
case OPTION_REGISTER -> {
System.out.println("----- Registration Page -----");
processRegistration(users);
}
case OPTION_RECOVER_PASSWORD -> {
System.out.println("----- Password Recovery Page -----");
processPasswordReset(users);
}
default -> System.out.println("Invalid selection, please try again.");
}
}
}
public static boolean processLogin(ArrayList<User> users) {
Scanner scanner = new Scanner(System.in);
int remainingAttempts = 3;
while (remainingAttempts > 0) {
System.out.print("Enter username: ");
String inputUsername = scanner.next();
if (!isUserExists(users, inputUsername)) {
System.out.println("Username not registered, please register first.");
return false;
}
System.out.print("Enter password: ");
String inputPassword = scanner.next();
while (true) {
String generatedCaptcha = generateCaptcha();
System.out.println("Captcha: " + generatedCaptcha);
System.out.print("Enter captcha: ");
String inputCaptcha = scanner.next();
if (inputCaptcha.equalsIgnoreCase(generatedCaptcha)) {
break;
} else {
System.out.println("Incorrect captcha, please try again.");
}
}
if (!checkCredentials(users, inputUsername, inputPassword)) {
remainingAttempts--;
System.out.printf("Incorrect username or password, %d attempts remaining%n", remainingAttempts);
} else {
System.out.println("Login successful!");
return true;
}
}
System.out.println("Too many failed attempts, please use password recovery.");
return false;
}
public static void processRegistration(ArrayList<User> users) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter username: ");
String newUsername = scanner.next();
while (isUsernameInvalid(users, newUsername)) {
System.out.print("Username invalid, please re-enter: ");
newUsername = scanner.next();
}
System.out.print("Enter password: ");
String newPassword = scanner.next();
System.out.print("Confirm password: ");
String confirmPassword = scanner.next();
while (!newPassword.equals(confirmPassword)) {
System.out.println("Passwords do not match, please re-enter:");
System.out.print("Enter password: ");
newPassword = scanner.next();
System.out.print("Confirm password: ");
confirmPassword = scanner.next();
}
String idCard;
while (true) {
System.out.print("Enter ID card number: ");
idCard = scanner.next();
if (isIdCardValid(idCard)) break;
System.out.println("Invalid ID card format, please try again.");
}
String phone;
while (true) {
System.out.print("Enter phone number: ");
phone = scanner.next();
if (isPhoneValid(phone)) break;
System.out.println("Invalid phone number format, please try again.");
}
users.add(new User(newUsername, newPassword, idCard, phone));
System.out.println("Registration completed successfully!");
}
public static void processPasswordReset(ArrayList<User> users) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your username: ");
String username = scanner.next();
if (!isUserExists(users, username)) {
System.out.println("Username is not registered.");
return;
}
String idCard;
while (true) {
System.out.print("Enter ID card number: ");
idCard = scanner.next();
if (isIdCardValid(idCard)) break;
System.out.println("Invalid ID card format, please try again.");
}
String phone;
while (true) {
System.out.print("Enter phone number: ");
phone = scanner.next();
if (isPhoneValid(phone)) break;
System.out.println("Invalid phone number format, please try again.");
}
if (verifyUserInfo(users, username, idCard, phone)) {
System.out.print("Enter new password: ");
String newPassword = scanner.next();
int userIndex = findUserIndex(users, username);
User existingUser = users.get(userIndex);
existingUser.setPassword(newPassword);
users.set(userIndex, existingUser);
System.out.println("Password updated successfully.");
} else {
System.out.println("Information does not match, password reset failed.");
}
}
public static String generateCaptcha() {
char[] allLetters = new char[52];
for (int i = 0; i < 26; i++) {
allLetters[i] = (char) ('A' + i);
allLetters[i + 26] = (char) ('a' + i);
}
Random random = new Random();
StringBuilder captchaBuilder = new StringBuilder();
for (int i = 0; i < 4; i++) {
int randomIndex = random.nextInt(allLetters.length);
captchaBuilder.append(allLetters[randomIndex]);
}
captchaBuilder.append(random.nextInt(10));
char[] captchaArr = captchaBuilder.toString().toCharArray();
int swapIndex = random.nextInt(captchaArr.length);
char temp = captchaArr[swapIndex];
captchaArr[swapIndex] = captchaArr[captchaArr.length - 1];
captchaArr[captchaArr.length - 1] = temp;
return new String(captchaArr);
}
public static boolean isUserExists(ArrayList<User> users, String username) {
for (User user : users) {
if (user.getUsername().equalsIgnoreCase(username)) {
return true;
}
}
return false;
}
public static boolean checkCredentials(ArrayList<User> users, String username, String password) {
for (User user : users) {
if (user.getUsername().equalsIgnoreCase(username)) {
return user.getPassword().equals(password);
}
}
return false;
}
public static boolean isUsernameInvalid(ArrayList<User> users, String username) {
if (username.length() < 3 || username.length() > 15) return true;
int digitCount = 0;
for (char c : username.toCharArray()) {
if (Character.isDigit(c)) digitCount++;
}
if (digitCount == username.length()) return true;
return isUserExists(users, username);
}
public static boolean isIdCardValid(String idCard) {
if (idCard.length() != 18) return false;
char[] arr = idCard.toCharArray();
if (arr[0] == '0') return false;
for (int i = 0; i < 17; i++) {
if (!Character.isDigit(arr[i])) return false;
}
return Character.isDigit(arr[17]) || arr[17] == 'X' || arr[17] == 'x';
}
public static boolean isPhoneValid(String phone) {
if (phone.length() != 11) return false;
char[] arr = phone.toCharArray();
if (arr[0] == '0') return false;
for (char c : arr) {
if (!Character.isDigit(c)) return false;
}
return true;
}
public static boolean verifyUserInfo(ArrayList<User> users, String username, String idCard, String phone) {
for (User user : users) {
if (user.getUsername().equalsIgnoreCase(username)) {
return user.getIdCardNumber().equals(idCard) && user.getPhoneNumber().equals(phone);
}
}
return false;
}
public static int findUserIndex(ArrayList<User> users, String username) {
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getUsername().equalsIgnoreCase(username)) {
return i;
}
}
return -1;
}
}
The book management core class provides full CRUD operations for books after successful authentication:
import java.util.ArrayList;
import java.util.Scanner;
public class BookManagementSystem {
private static final String OPTION_ADD = "1";
private static final String OPTION_SEARCH = "2";
private static final String OPTION_DELETE = "3";
private static final String OPTION_UPDATE = "4";
private static final String OPTION_LIST = "5";
private static final String OPTION_EXIT = "6";
private static ArrayList<Book> bookCatalog = new ArrayList<>();
static {
bookCatalog.add(new Book(101, "TheMoonAndSixpence", "SomersetMaugham", 58));
bookCatalog.add(new Book(102, "Sapiens", "YuvalHarari", 88));
bookCatalog.add(new Book(103, "NineteenEightyFour", "GeorgeOrwell", 42));
}
public void startManagementInterface() {
showManagementMenu(bookCatalog);
}
public void showManagementMenu(ArrayList<Book> books) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("===== Book Management =====");
System.out.println("1. Add Book 2. Search Book 3. Delete Book");
System.out.println("4. Update Book 5. List All Books 6. Exit");
System.out.println("============================");
String selection = scanner.next();
switch (selection) {
case OPTION_ADD -> {
System.out.println("--- Add New Book ---");
addNewBook(books);
}
case OPTION_SEARCH -> {
System.out.println("--- Search Book ---");
System.out.print("Enter book title to search: ");
String title = scanner.next();
searchBookByTitle(books, title);
}
case OPTION_DELETE -> {
System.out.println("--- Delete Book ---");
System.out.print("Enter book ID to delete: ");
int id = scanner.nextInt();
deleteBookById(books, id);
}
case OPTION_UPDATE -> {
System.out.println("--- Update Book Information ---");
System.out.print("Enter book ID to update: ");
int id = scanner.nextInt();
updateBookInfo(books, id);
}
case OPTION_LIST -> {
System.out.println("--- All Books in Catalog ---");
listAllBooks(books);
}
case OPTION_EXIT -> {
System.out.println("Thank you for using Library Management System");
System.exit(0);
}
default -> System.out.println("Invalid option, please try again.");
}
}
}
public static void addNewBook(ArrayList<Book> books) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of books to add: ");
int count = scanner.nextInt();
for (int i = 0; i < count; i++) {
Book newBook = new Book();
System.out.print("Enter book ID: ");
int bookId = scanner.nextInt();
while (isBookIdExists(books, bookId)) {
System.out.print("Book ID exists, please enter another ID: ");
bookId = scanner.nextInt();
}
newBook.setBookId(bookId);
System.out.print("Enter book title: ");
newBook.setBookTitle(scanner.next());
System.out.print("Enter author name: ");
newBook.setAuthor(scanner.next());
System.out.print("Enter book price: ");
newBook.setPrice(scanner.nextInt());
books.add(newBook);
}
System.out.println("All books added successfully.");
}
public static void deleteBookById(ArrayList<Book> books, int bookId) {
for (int i = 0; i < books.size(); i++) {
if (books.get(i).getBookId() == bookId) {
books.remove(i);
System.out.println("Book deleted successfully.");
return;
}
}
System.out.println("Book with the given ID not found.");
}
public static void searchBookByTitle(ArrayList<Book> books, String title) {
for (Book book : books) {
if (book.getBookTitle().equalsIgnoreCase(title)) {
System.out.printf("ID: %d | Title: %s | Author: %s | Price: %d%n",
book.getBookId(), book.getBookTitle(), book.getAuthor(), book.getPrice());
return;
}
}
System.out.println("No matching book found.");
}
public static void updateBookInfo(ArrayList<Book> books, int bookId) {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < books.size(); i++) {
if (books.get(i).getBookId() == bookId) {
System.out.print("Enter new book title: ");
String newTitle = scanner.next();
System.out.print("Enter new author name: ");
String newAuthor = scanner.next();
System.out.print("Enter new price: ");
int newPrice = scanner.nextInt();
Book updatedBook = new Book(bookId, newTitle, newAuthor, newPrice);
books.set(i, updatedBook);
System.out.println("Book information updated successfully.");
return;
}
}
System.out.println("Book with the given ID not found.");
}
public static void listAllBooks(ArrayList<Book> books) {
System.out.printf("%-8s %-30s %-20s %-6s%n", "Book ID", "Title", "Author", "Price");
for (Book book : books) {
System.out.printf("%-8d %-30s %-20s %-6d%n",
book.getBookId(), book.getBookTitle(), book.getAuthor(), book.getPrice());
}
}
public static boolean isBookIdExists(ArrayList<Book> books, int bookId) {
for (Book book : books) {
if (book.getBookId() == bookId) {
return true;
}
}
return false;
}
}