OneCompiler

q1

1726

import java.util.ArrayList;
import java.util.Scanner;

class UserManagement {
// Class to store user details
static class User {
String username;
String password;

    User(String username, String password) {
        this.username = username;
        this.password = password;
    }
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    ArrayList<User> users = new ArrayList<>(); // To store registered users

    while (true) {
        // Display menu
        System.out.println("\nSelect an option:");
        System.out.println("1. User Registration");
        System.out.println("2. Log in");
        System.out.println("3. Exit");
        System.out.print("Enter your choice: ");
        int choice = scanner.nextInt();
        scanner.nextLine(); // Consume newline

        if (choice == 1) {
            // User Registration
            System.out.print("Enter a username: ");
            String username = scanner.nextLine();
            System.out.print("Enter a password: ");
            String password = scanner.nextLine();
            users.add(new User(username, password)); // Add user to the list
            System.out.println("User registered successfully!");
        } else if (choice == 2) {
            // User Login
            System.out.print("Enter your username: ");
            String username = scanner.nextLine();
            System.out.print("Enter your password: ");
            String password = scanner.nextLine();

            boolean loginSuccessful = false;
            for (User user : users) {
                if (user.username.equals(username) && user.password.equals(password)) {
                    loginSuccessful = true;
                    break;
                }
            }

            if (loginSuccessful) {
                System.out.println("Login successful! Welcome, " + username + "!");
            } else {
                System.out.println("Invalid username or password. Please try again.");
            }
        } else if (choice == 3) {
            // Exit
            System.out.println("Exiting the program. Goodbye!");
            break;
        } else {
            System.out.println("Invalid choice. Please try again.");
        }
    }
    scanner.close();
}

}