Boolean help: Testing the parameters for a password JAVA [duplicate] - java

This question already has answers here:
How to check whether a string contains lowercase letter, uppercase letter, special character and digit?
(6 answers)
Closed 7 years ago.
Task:
This program should check if an entered password is at least 8 characters long, one upper and lowercase letter, a number, and a special character.
Code:
String password;
boolean hasLength;
boolean hasUppercase;
boolean hasLowercase;
boolean hasDigit;
boolean hasSpecial;
Scanner scan = new Scanner(System.in);
/******************************************************************************
* Inputs Section *
******************************************************************************/
System.out.println("A password must be at least 8 character long");
System.out.println("And must contain:");
System.out.println("-At least 1 number");
System.out.println("-At least 1 uppercase letter");
System.out.println("-At least 1 special character (!##$%^&*()_+)\n");
System.out.print("Please enter your new password: ");
password = scan.nextLine();
/******************************************************************************
* Processing Section *
******************************************************************************/
System.out.print("\n");
System.out.println("Entered Password:\t " + password);
hasLength = password.length() < 8; // parameters for length
// for lower and uppercase characters
hasUppercase = !password.equals(password.toUpperCase());
hasLowercase = !password.equals(password.toLowerCase());
hasDigit = !password.matches("[0-9]");//checks for digits
hasSpecial = !password.matches("[A-Za-z]*"); //for anything not a letter in the ABC's
// the following checks if any of the instances are false, of so prints the statement
if(hasLength)
{
System.out.println("Verdict: Invalid, Must have at least 8 characters");
}
if(!hasUppercase)
{
System.out.println("Verdict: Invalid, Must have an uppercase Character");
}
if(!hasLowercase)
{
System.out.println("Verdict: Invalid, Must have a lowercase Character");
}
if(!hasDigit)
{
System.out.println("Verdict: Invalid, Must have a number");
}
if(!hasSpecial)
{
System.out.println("Verdict: Invalid, Must have a special character");
}
If I input the password 'water' and I get:
Entered Password: water
Verdict: Invalid, Must have at least 8 characters
Verdict: Invalid, Must have a lowercase Character
Verdict: Invalid, Must have a special character

I think the upper and lowercase checks should be done vice-versa:
hasUppercase = !password.equals(password.toLowerCase());
hasLowercase = !password.equals(password.toUpperCase());
Because the lowercase version of the password equals the password, only if it does not contains uppercase letters.
The other two check can be done like this:
hasDigit = password.matches(".*[0-9].*");
hasSpecial = !password.matches("[A-Za-z0-9]*");

Related

Need to validate code inputted by user which include letters and numbers

Basically I want the user to enter a code in this format - XXXX000 and if the user enters 3 letters and 4 digits for example - it outputs an error.
What i did is that i wrote a command that input has to be maximum 7 characters but it doesn't specify what the characters need to be. Therefore if user enters 7 digits, it is still accepted which it should not.
System.out.print("Enter the animal's unique code - Format: (XXXX111)");
String codein = in.nextLine();
a.setCode(codein);
if (codein.length() != 7) {
System.out.println("Format was not met, please try again");
System.out.println("Enter the animal's unique code - Format: (XXXX111)");
codein = in.nextLine();
a.setCode(codein);
}
An error should appear if user does not enter in this format XXXX000
Assuming that X means A-Z and a-z and 0 means 0-9 in your pattern, you can use this pattern to valid the code:
[A-Za-z]{4}\d{3}
For more info on regexes, see here.
Use it like this:
if (codeine.matches("[A-Za-z]{4}\\d{3}")) {
// valid
} else {
// invalid
}

I want to know how to find a special character in a string

I am programming in Java in Eclipse, I want to ask users to enter their specific ID, Which starts with an uppercase G and has 8 digit numbers. like G34466567. if the user enters an invalid ID it will be an error. how can i separate a valid ID from others?
You can use regex. This pattern checks if the first character is a capital G and there are 8 digits following:
([G]{1})([0-9]{8})$
As you see there are two expressions which are separated by the (). The first says "only one character and this one has to be a capital G". And the second one says, there have to be 8 digits following and the digits can be from 0 to 9.
Every condition contains two "parts". The first with the [] defines which chars are allowed. The pattern inside the {} show how many times. The $ says that the max length is 9 and that there can't be more chars.
So you can read a condition like that:
([which chars are allowed]{How many chars are allowed})
^------------------------\/---------------------------^
One condition
And in Java you use it like that:
String test= "G12345678";
boolean isValid = Pattern.matches("([G]{1})([0-9]{8})$", test);
As you see that matches method takes two parameters. The first parameter is a regex and the second parameter is the string to check. If the string matches the pattern, it returns true.
Create an ArrayList. Ask the user to input the ID, check if it is already there in the list, ignore, otherwise add that ID to the list.
EDIT: For ensuring that the rest 8 characters of the String ID are digits, you can use the regex "\\d+". \d is for digits and + is for one or more digits.
Scanner sc = new Scanner(System.in);
ArrayList<String> IDS = new ArrayList();
char more = 'y';
String ID;
String regex = "\\d+";
while (more == 'y') {
System.out.println("Pleaes enter you ID.");
ID = sc.next();
if (IDS.contains(ID)) {
System.out.println("This ID is already added.");
} else if (ID.length() == 9 && ID.charAt(0) == 'G' && ID.substring(1).matches(regex)) {
IDS.add(ID);
System.out.println("Added");
} else {
System.out.println("Invalid ID");
}
System.out.println("Do you want to add more? y/n");
more = sc.next().charAt(0);
}
Assuming that you save the id as a string, you can check the first letter and then check if the rest is a number.
Ex.
String example = "G12345678";
String firstLetter = example.substring(0, 1); //this will give you the first letter
String number = example.substring(1, 9); //this will give you the number
To check that number is a number you could do the following instead of checking every character:
try {
foo = Integer.parseInt(number);
} catch (NumberFormatException e) {
//Will Throw exception!
//do something! anything to handle the exception.
// this is not a number
}

Do-While loop issue, making the prompt run again -JAVA

I am attempting to make it so this program runs again if the user enters 'y'. What happens when the user does this is the program runs again, but not correctly. This is what I have so far. I know a do while loop will be best for this. Is it an error in how the variables are initialized?
String password;
boolean hasLength;
boolean hasUppercase;
boolean hasLowercase;
boolean hasDigit;
boolean hasSpecial;
String runAgain = "";
Scanner scan = new Scanner(System.in);
/******************************************************************************
* Inputs Section *
******************************************************************************/
do {
System.out.println("A password must be at least 8 character long");
System.out.println("And must contain:");
System.out.println("-At least 1 number");
System.out.println("-At least 1 uppercase letter");
System.out.println("-At least 1 special character (!##$%^&*()_+)\n");
System.out.print("Please enter your new password: ");
password = scan.nextLine();
/******************************************************************************
* Processing Section *
******************************************************************************/
System.out.print("\n");
System.out.println("Entered Password:\t" + password);
hasLength = password.length() < 8; // parameters for length
// for lower and uppercase characters
hasUppercase = !password.equals(password.toLowerCase()); //lowercase version of the password equals the password,
hasLowercase = !password.equals(password.toUpperCase()); //only if it does not contain uppercase letters.
hasDigit = password.matches(".*[0-9].*");//checks for digits
hasSpecial = !password.matches("[A-Za-z0-9]*"); //for anything not a letter in the ABC's
//prints the verdict
System.out.print("Verdict: ");
if(hasLength)
{
System.out.println("\t\tInvalid, Must have at least 8 characters");
}
if(!hasUppercase)
{
System.out.println("\t\t\tInvalid, Must have an uppercase character");
}
if(!hasLowercase)
{
System.out.println("\t\t\tInvalid, Must have a lowercase character");
}
if(!hasDigit)
{
System.out.println("\t\t\tInvalid, Must have a number");
}
if(!hasSpecial)
{
System.out.println("\t\t\tInvalid, Must have a special character");
}
System.out.print("Would you like to make another password? (Y/N) ");
runAgain = scan.next();
System.out.println("\n");
} while (runAgain.equalsIgnoreCase("Y"));
which gives this output when yes is entered to run again. It skips the prompt entirely.
Would you like to make another password? (Y/N) y
A password must be at least 8 character long
And must contain:
-At least 1 number
-At least 1 uppercase letter
-At least 1 special character (!##$%^&*()_+)
Please enter your new password:
Entered Password:
Verdict: Invalid, Must have at least 8 characters
Invalid, Must have an uppercase Character
Invalid, Must have a lowercase character
Invalid, Must have a number
Invalid, Must have a special character
Would you like to make another password? (Y/N)
You would need to read the complete line form console at runAgain = scan.next();. Just single token is being read to runAgain and the console is left with \r or Return character which will be read as next password where you do scan.nextLine(). You may change the statement to runAgain = scan.nextLine().trim();.
System.out.print("Would you like to make another password? (Y/N) ");
// runAgain = scan.next();
runAgain = scan.nextLine();
System.out.println("\n");

Using while loop to validate password in Java

The prompt is to have a user input a password and the password must be at least 8 characters with no white spaces, must have one upper case letter, and must have one digit. It has to use a while loop. If the password conforms it should output "password ok" or otherwise say "try again"
Anyone know what to do for this?
All I can pretty much do is the scanner and user input
Use 2 boolean flags. One each for checking presence of digit, uppercase letter. Your condition could go like :
//loop start
{
if(string.charAt(i)==space){
print "not valid"
return false;
}
// check for capital letter here and set flag to true if it is found.
// check digit here and set that flag to true if found.
}//loop end
// outside the loop make these checks
if(string.length>8 && isCapitalFound && isDigitFound)
//print "valid"
return true
I made your home work for you:
boolean noWhite = false;
boolean oneUppercase = false;
boolean oneDigit = false;
Scanner scan = new Scanner(System.in);
String pass = "";
while (!noWhite || !oneUppercase || !oneDigit || pass.length() < 8) {
System.out.print("new pass: ");
pass = scan.next();
noWhite = !pass.contains(" ");
oneUppercase = !pass.equals(pass.toLowerCase());
oneDigit = pass.matches(".*\\d.*");
}
System.out.println("OK");

Searching a string for a non-letter character in a loop

So let's imagine we have this loop that obtains input from the user in the form of strings. With that input, what we want to do is set up a set of validations that will check if certain criteria are met. If all of these conditions are met, it'll complete the action in question. However; if it doesn't, it'll tell them the error and restart the process.
My question is about validating the existance (or non-existance) of a letter in a string. I have this program and for one of these validations, I need to check the entire string. If the string does not have at least one character that isn't a letter, I want to halt the action and explain that a non-letter character is required.
The problem is that I am not sure how I could replicate this in an expression in an if loop. Here's what I have so far.
public static changePassword() // Method that runs through the process of changing the password.
{
// Retrieving the current and new password from the user input.
System.out.println("Welcome to the change password screen.");
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your current password: ");
String currentPassword = keyboard.nextLine();
System.out.print("Please enter the new password: ");
String newPassword1 = keyboard.nextLine();
System.out.print("Please enter the new password again: ");
String newPassword2 = keyboard.nextLine();
// Validating the new password entry.
if (newPassword1.equals(newPassword2)) // Checking to see if the new password was entered exactly the same twice.
{
if (newPassword1.length() >= 6) // Checking to see if the new password has 6 or more characters.
{
if (**some expression**) // Checking to see if the password has at least one non-letter character.
{
currentPassword = newPassword1 // If all conditions are met, it sets the current password to the password entered by the user.
}
else // If there isn't a non-letter character, it informs the user and restarts the process.
{
System.out.println("The new password must have a non-letter character.");
changePassword();
}
}
else // If there is less than 6 characters, it informs the user and restarts the process.
{
System.out.println("The new password can not be less than 6 characters.");
changePassword();
}
}
else // If the new passwords don't match, it informs the user and restarts the process.
{
System.outprintln("The passwords must match.");
changePassword();
}
}
Assuming by "letter" you mean an english character in A-Z, a-z, just iterate through the string and return true if you encounter a character whose int value is outside the letter range.
public static boolean containsNonLetter(String s){
for(int i = 0; i < s.length(); i++){
int ind = (int)s.charAt(i);
if(ind < 65 || (ind > 90 && ind < 97) || ind > 122)
return true;
}
return false;
}
I am making the assumption that by letter you meant alphabets. If you use regex pattern you can have a very clean code as well you have ability to update the pattern as necessary. To learn more check Java Pattern. Here is the code.
private static final Pattern APLHA = Pattern.compile("\\p{Alpha}");
public static boolean hasLetter(String input) {
return APLHA.matcher(input).find();
}

Categories

Resources