The below are the instructions and my code that I have tried so far. I am almost done but just having problems with part four. So the expected output should be:
Please enter a password: abc
Password much have at least 8 characters
Please enter a password: abcd1234$
Password must only contain letter and digits
Please enter a password: ####
Password must have at least 8 characters
Password must only contain letters and digits
Please enter a password: abcd1234
Password accepted!
When I type abc this is what I get:
Please enter password and then hit enter:abc
Password must have at least 8 characters
Password Accepted
When I do this the program ends! Could someone help me with this?
Problem
- Write a program that prompts the user to enter a password.
- Create a boolean variable named valid and set it to true. If any of these tests below fail, set it to true.
- Check the password to see if it has at least 8 characters. If it does not, display the message, "Password must have at least 8 characters"
Check the password to see if it consists of only letter and digits. To do this, you will need to loop through all of the characters in the string. A character c is a letter of digit if this expression is true:
('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9')
if this is even not true, break from your loop and display the message, "Password must contain only letter and digits" 5. If valid is still true at the end of the program, display the message, "Password accepted!"
My code
import java.util.Scanner;
public class PasswordVerification {
public static void main(String[] args) {
//Creates a scanner
Scanner sc = new Scanner(System.in);
boolean valid = false;
String password;
//Asks user to enter password
System.out.print("Please enter password and then hit enter:");
password = sc.nextLine();
//Checks to see if password is at least 8 characters.
if (password.length()<8)
{
valid = false;
System.out.println("Password must have at least 8 characters");
}
//Checks each character to see if it is acceptable.
for (int i = 0; i < password.length(); i++){
char c = password.charAt(i);
if ( ('a' <= c && c <= 'z') // Checks if it is a lower case letter
|| ('A' <= c && c <= 'Z') //Checks if it is an upper case letter
|| ('0' <= c && c <= '9') //Checks to see if it is a digit
)
{
valid = true;
}
else
{
// tells the user that only letters & digits are allowed
System.out.println("Only letter & digits are acceptable.");
valid = false;
break;
}
}
// if the password is valid, tell the user it's accepted
System.out.println("Password Accepted");
}
}