Question: CODE Works fine, (thanks to Uday!), but my code blows up when I try to add a statement to make certain the user enters 'y'

CODE Works fine, (thanks to Uday!), but my code blows up when I try to add a statement to make certain the user enters 'y' or 'n' ONLY to the String userChoice. The prompt is " Do you wish to exit the system? (y/n): "; User MUST input 'y' or 'n'...if they don't, I'm trying to System.out.println("Invalid input. Please enter 'y' or 'n'.");

Then I'm trying to get my code to validate the userName FIRST, (before prompting for user password). If the userName is invalid; "Invalid username. Please enter valid username.!" and when the user enters a valid username, then go to "Enter password"...and if they don't enter a valid password, "Invalid password. Please enter valid password!".

package newzooauthentication;

import java.io.File; import java.security.MessageDigest; import java.util.Scanner;

public class NewZooAuthentication { /** * * @param args the command line arguments * @throws Exception * **/

// Main method public static void main(String[] args) throws Exception { //<---->Variable to keep track of the number of log-in attempts int loginAttempts = 0; //<---->Scanner object to read input from the console Scanner readUserInput = new Scanner(System.in); //<---->Create objectName to call memberMethod in class authentication authentication userCreds = new authentication(); //<---->Begin while loop until break encountered //<---->(user exits system or 3 unsuccessful log-in //<---->attempts are made) while (true) { //<-------->Request user input username System.out.print("Enter username: "); //<-------->Set String variable equal to user input String userName = readUserInput.nextLine(); //<-------->Request user input password System.out.print("Enter password: "); //<-------->Set String variable equal to user input String userPwd = readUserInput.nextLine(); //<-------->Boolean variable declared to verify credentials //<-------->Set equal to objectName with dot separater which //<-------->calls memberMethod with parameters from class authentication boolean credsAuthentic = userCreds.areCredsValid(userName, userPwd);

//<-------->Begin nested control structure //<-------->If Boolean variable evaluates to true, authorization message //<-------->has been displayed, ask user if they wish to exit the system if (credsAuthentic) { System.out.print(" Do you wish to exit the system? (y/n): "); String userChoice = readUserInput.nextLine(); //<------------>If the user chooses 'y', exit the system; //<------------>otherwise, reset counter and loop back to log-in request if (userChoice.toLowerCase().charAt(0) == 'y') { System.out.println(" Goodbye" + " " + userName + "!" + " User has logged off! "); break; // Program halted by user } else { loginAttempts = 0; // Reset log-in attempts System.out.println(""); } } //<-------->If Boolean variable evaluates to false, //<-------->increment variable loginAttempts else { loginAttempts++; //<------------>If loginAttempts variable threshold IS met, //<------------>tell the user so and exit the system if (loginAttempts == 3) { System.out.println(" Maximum number of failed attempts reached!" + " Exiting system...Goodbye! "); break; } //<------------>If loginAttempts threshold is NOT met allow the user additional log-in //<------------>attempts until log-in IS successful OR loginAttempts threshold is met //<------------>Let the user know how many attempts they have left until system exits else { System.out.println(" Invalid username or password..." + " Please enter valid credentials!" + " You have" + " " + (3 - loginAttempts) + " " + "attempt(s) left."); System.out.println(""); } } } } }

// Begin new class for verifying username and password class authentication { // memberMethod with parameters to validate the user id and password public boolean areCredsValid(String userName, String userPwd) throws Exception { //<---->Scanner object to read from credentials.txt file Scanner readCFile = new Scanner(new File("Credentials.txt")); //<---->Boolean variable declared and set boolean credsAuthentic = false; //<---->Copied and pasted code section to convert the //<---->password with MessageDigest-5 (MD5) hash MessageDigest md = MessageDigest.getInstance("MD5"); md.update(userPwd.getBytes()); byte[] digest = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : digest) { sb.append(String.format("%02x", b & 0xff)); } //<----->End copied and pasted code section //<---->While Loop to read user information in the //<---->credentials.txt file until End Of File (EOF) while (readCFile.hasNextLine()) { //<-------->Parse the contents of credentials.txt file String credInfo = readCFile.nextLine(); String parsedInfo[] = credInfo.split("\t"); String nameValue = parsedInfo[0].trim(); String hashValue = parsedInfo[1].trim(); String roleValue = parsedInfo[3].trim(); //<-------->Comparing parsed nameValue to username input if (nameValue.equalsIgnoreCase(userName)) { //<------------>Comparing parsed hashValue to password input if (hashValue.equals(sb.toString())) { //<---------------->If nameValue and hashValue match user input // <--------------->set Boolean variable to true (log-in successful) credsAuthentic = true; //<---------------->Read the matching role text file returned from roleValue //<---------------->(i.e. admin.txt; veterinarian.txt; zookeeper.txt) Scanner readRFile = new Scanner(new File(roleValue.concat(".txt")));

// <---------------->Display authorization message stored in the matching role text file // <---------------->(i.e. admin.txt; veterinarian.txt; zookeeper.txt) while (readRFile.hasNextLine()) { System.out.println(""); System.out.print(readRFile.nextLine()); } break; // End while loop for reading role file } } } //<---->Close credentials.txt file readCFile.close(); return credsAuthentic; } }

TEXT FILES:

credentials.txt

griffin.keyes 108de81c31bf9c622f76876b74e9285f "alphabet soup" zookeeper rosario.dawson 3e34baa4ee2ff767af8c120a496742b5 "animal doctor" admin bernie.gorilla a584efafa8f9ea7fe5cf18442f32b07b "secret password" veterinarian donald.monkey 17b1b7d8a706696ed220bc414f729ad3 "M0nk3y business" zookeeper jerome.grizzlybear 3adea92111e6307f8f2aae4721e77900 "grizzly1234" veterinarian bruce.grizzlybear 0d107d09f5bbe40cade3de5c71e9e9b7 "letmein" admin

admin.txt

Hello, System Admin!

As administrator, you have access to the zoo's main computer system. This allows you to monitor users in the system and their roles.

veterinarian.txt

Hello, Veterinarian!

As veterinarian, you have access to all of the animals' health records. This allows you to view each animal's medical history and current treatments/illnesses (if any), and to maintain a vaccination log.

zookeeper.txt

Hello, Zookeeper!

As zookeeper, you have access to all of the animals' information and their daily monitoring logs. This allows you to track their feeding habits, habitat conditions, and general welfare.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!