Question

Create a class called Login which contains a HashMap as a private attribute. It should also have an instance method called lo
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

Please find the code below, also go through the comments provided to make the code readable. I am enclosing the screenshots of execution of the program with 3 different cases.

  • Invalid username
  • Valid username and invalid password
  • Valid username and password

Valid username and invalid password

Run: Login x /usr/lib/jvm/java-8-oracle/bin/java ... Please enter the username : Bonnie Please enter the password : 1111 The

Valid username and password

Run: Login /usr/lib/jvm/java-8-oracle/bin/java ... Please enter the username : Bonnie Please enter the password : 3333 Thank

Invalid username

Run: Login /usr/lib/jvm/java-8-oracle/bin/java ... Please enter the username : stranger Please enter the password : 1234 The

import java.util.HashMap;
import java.util.Scanner;

public class Login {

    // Class attributes a Hashmap & 2 String arrays
    private HashMap<String, String> credentials = new HashMap<>();
    private static String [] userNameArray = { "John", "Steve", "Bonnie", "Kylie", "Logan", "Robert"};
    private static String [] passwordArray = { "1111", "2222", "3333", "4444", "5555", "6666"};

    // Getters for 2 arrays
    public static String[] getUserNameArray() {
        return userNameArray;
    }

    public static String[] getPasswordArray() {
        return passwordArray;
    }

    // This method loads the HashMap with username and password
    public void loadCredentials(String [] userName, String [] password){
        for (int i=0; i<userName.length; i++){
            credentials.put(userName[i],password[i]);
        }
    }

    /*  This method verifies the username and password
        If the username entered by user doesn't exists then an error message is thrown
        If the username entered by the user exists but password entered doesn't match, then error is thrown to the user
     */
    public void login(){
        String userName, passWord;

        // Ask the user for username
        System.out.println("Please enter the username : ");
        Scanner sc1 = new Scanner(System.in);
        userName = sc1.nextLine();

        // Ask the user for password
        System.out.println("Please enter the password : ");
        Scanner sc2 = new Scanner(System.in);
        passWord = sc2.nextLine();

        // Verify whether the username entered by the user exists in the hashmap
        if (credentials.containsKey(userName)){

            // get the corresponding password for the username entered by the user
            String correspondingPwd = credentials.get(userName); // gets the password for the username

            // Verify whether the username matches with the password
            if (credentials.containsKey(userName) && correspondingPwd.equals(passWord)){
                System.out.println("Thank you, credentials matched :");
            }else{
                System.out.println("The PASSWORD did not match :");
            }
        }else{ // If the username doesn't exist, then simply throw an error message

            System.out.println("The USER doesn't exist -");
        }

    }

    public static void main(String [] args){ // main method

        Login loginObj = new Login(); // Create an obj of class Login

        // As both the arrays are static, we can directly call without an object
        loginObj.loadCredentials(getUserNameArray(),getPasswordArray()); 
        
        // calling login method which has the logic to verify the credentials
        loginObj.login();

    } // end of main
} // end of program

Thank you,

All the best !!!

Add a comment
Know the answer?
Add Answer to:
Create a class called Login which contains a HashMap as a private attribute. It should also...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hashmap concept

    HashMap:  We can use a HashMap to store key value pairs.  Reminder that only reference types can be used as the key or value.  It you want to use a number as the key then an Integer data type could be used but not an int primitive data type.Create a class called Login which contains a HashMap as a private attribute.  It should also have an instance method called loadCredentials which accepts the two arrays.  It will load the HashMap...

  • 3. Design and implement a class called ClassStats, in a file called stats.py, that includes: •...

    3. Design and implement a class called ClassStats, in a file called stats.py, that includes: • private attributes for a student number and status (pass or fail), • private class variables to keep track of the total number of students with status pass and the total number of students with status fail, • a constructor with default values (empty strings) for all instance variables, • an accessor method for each instance variable and also for the class vari- ables, •...

  • Can someone fix the program below so it does what the picture says it won't work...

    Can someone fix the program below so it does what the picture says it won't work for me. import java.util.Scanner; public class Userpass { static String arr[]; static int i = 0; public static void main(String[] args) { String username, password; int tries = 0, result; do { System.out.print("Enter the username: "); username = readUserInput(); System.out.print("Enter the password: "); password = readUserInput(); result = verifyCredentials(username, password); tries++; if (result == -1) System.out.println("The username is incorrect!\n"); else if (result == -2)...

  • need help in Java Now we’ll continue our project by writing a Facebook class that contains an ArrayList of Facebook user...

    need help in Java Now we’ll continue our project by writing a Facebook class that contains an ArrayList of Facebook user objects. The Facebook class should have methods to list all of the users (i.e. print out their usernames), add a user,delete a user, and get the password hint for a user You will also need to create a driver program. The driver should create an instance of the Facebook class and display a menu containing five options: list users...

  • 1) Given the following “BasicAccount” class #include <iostream> #include <string> class BasicAccount {    private:      ...

    1) Given the following “BasicAccount” class #include <iostream> #include <string> class BasicAccount {    private:       std::string m_username ;       std::string m_password ;    public:       BasicAccount(std::string username, std::string password)       {          m_username = username ;          m_password = password ;       }               virtual std::string toString()       {          return "USERNAME(" + m_username + ") PASSWORD(" + m_password + ")" ;       }          std::string getUserName()       {          return m_username ;       }      virtual...

  • Create a new class called DemoSortingPerformacne Create a private method called getRandomNumberArray. It returns an array...

    Create a new class called DemoSortingPerformacne Create a private method called getRandomNumberArray. It returns an array of Integer and has 2 parameters: arraySize of type int and numberOfDigits of type int. This method should create an array of the specified size that is filled with random numbers. Each random numbers should have the same number of digits as specified in the second parameter In your main method (or additional private methods) do the following: Execute selection sort on quick sort...

  • Create a class called Reverse that reverses an array of integers. The class should have two...

    Create a class called Reverse that reverses an array of integers. The class should have two method: - public static void reverse(int [] array) – Which calls the private recursive method, passing the array parameter and which two array elements should be swapped. - private static void reverseRecursive(int [] array, int startIndex, int endIndex) – Which swaps the two elements of the array parameter pointed to by the startIndex and endIndex parameters. The method should be called again, this time,...

  • Write the following in Java Design a class called ReviewSystem, this class should have an attribute...

    Write the following in Java Design a class called ReviewSystem, this class should have an attribute reviewList, which is an ArrayList type. add a constructor to initialize the attribute. add a method addReviewAndComment(). This method asks from the user to provide an integer (0 to 4 for the five ratings) and a String as a comment. If the user inputs -1, it ends the loop of asking. All valid user inputs should be saved to the reviewList attribute. For example:...

  • Code should be in C# Create a class called SavingsAccount.  Use a static variable called annualInterestRate to...

    Code should be in C# Create a class called SavingsAccount.  Use a static variable called annualInterestRate to store the annual interest rate for all account holders.  Each object of the class contains a private instance variable savingsBalance, indicating the amount the saver currently has on deposit. Provide method CalculateMonthlyInterest to calculate the monthly interest by multiplying the savingsBalance by annualInterestRate divided by 12 – this interest should be added to savingsBalance.  Provide static method setAnnualInterestRate to set the annualInterestRate to a new value....

  • In Java: Requirements: 1. Create a class called Bike. 2. Create these private attributes: int currentSpeed...

    In Java: Requirements: 1. Create a class called Bike. 2. Create these private attributes: int currentSpeed int currentGear String paintColor 3. Create a constructor that takes 2 arguments: speed, gear, color. 4. Create another constructor that takes no arguments. 5. Create a method called goFaster(int amount) which increases the speed by the given amount. 6. Create a method called brake() which sets the speed to 0. 7. Create a method called print() which describes the bike and the speed it...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT