Using while loop to validate password in Java - 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");

Related

How can I get my java program to include uppercase and lowercase characters?

I am trying to include uppercase and lowercase letters for my available characters in my code but I am not sure how to go about this. Can anyone give me some insight?
Following is what I have so far for my code:
import java.util.Scanner;
public class ShopSign {
public static void main(String[] args) {
// Scanner class//
Scanner input = new Scanner(System.in);
// variable to store available characters//
String availableCharacters;
// variable to store proposed message//
String proposedMessage;
// variable to keep track if message will make it or not to the sign board//
boolean flag = true;
// variable to store the character that remain short//
char shortCharacter = ' ';
// variable to store character at current position//
char temp;
// Prompt for input of available characters//
System.out.println("Enter available characters:");
// read available characters
availableCharacters = input.nextLine();
// Prompt for input of proposed message//
System.out.print("Enter proposed message: ");
// read proposed message//
proposedMessage = input.nextLine();
// remove white spaces from the message//
proposedMessage = proposedMessage.replaceAll("\\s","");
//check if character it is available//
for(int i = 0; i < proposedMessage.length(); i++){
temp = proposedMessage.charAt(i);
// if character is not the whitespace//
if(temp != ' '){
// check if character is available//
if(availableCharacters.indexOf(temp) >= 0){
// replace the character to empty string from available characters//
availableCharacters = availableCharacters.replaceFirst(Character.toString(temp), "");
}
// otherwise mark the flag false and break the loop//
else{
flag = false;
shortCharacter = temp;
break;
}
}
}
// Print the appropriate message to the user//
if(flag){
System.out.println("The message makes it to the sign board.");
}
else{
System.out.println("We are short of character "+ Character.toString(shortCharacter) +".");
}
input.close();
}
}
What exactly are you hoping to do? After using your code and using aAbB for the available letters, I then entered AaBb as my proposed message and it outputted "This message makes it to the sign board."
EDIT; If you are looking to only allow ONE of any character (upper-case AND lower-case) you can do:
availableCharacters = availableCharacters.replaceFirst(Character.toString(temp).toLowerCase(), "");
availableCharacters = availableCharacters.replaceFirst(Character.toString(temp).toUpperCase(), "");
Your expectation is not clear, but i have suggestion on your code:
don't need check if(temp != ' ') because you already cleared space
char on previous code :
proposedMessage = proposedMessage.replaceAll("\s","");
your code will fail in case proposedMessage contains special
characters (Example : +\...)
Need to use Pattern.quote before using replaceFirst :
String pattern = Pattern.quote(Character.toString(temp));
availableCharacters = availableCharacters .replaceFirst(pattern, "");

Java Password Checker

My problem is to create a password that contains between 6 and 10 characters and contains at least one letter and one digit, and then to have the user re-enter the password and confirm that they match.
The only issue I have is checking to see if the password has a letter or digit. I have browsed and found the same problem on the website, but I was confused about some of the methods and other things they referenced in their code since I seemed to build mine differently. I thought about using the indexOf() method to see if it returned a -1 value, but I'm not really sure where to begin.
I'm really new at java and I'm sure there is a much more efficient way to construct this, and I would love any tips.
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
//Input from user
String password;
Scanner input = new Scanner(System.in);
System.out.print("Please create your password: ");
password = input.nextLine();
//Checking password length
while( (password.length() < 6) || (password.length() > 10) )
{
System.out.print("This password must be between 6 and 10 characters. Try again: ");
password = input.nextLine();
}
//Checking to see if passwords contain digit/letter
/*Need to add code here */
//Confirming if passwords match
String password2;
System.out.print("\nPlease type your password again to confirm: ");
password2 = input.nextLine();
while( !password2.equals(password) )
{
System.out.print("Those passwords do not match. Try again: ");
password2 = input.nextLine();
}
}
}
With Regex
You should use a regular expression, to check for theese crits.
First, the code:
pwd.matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$")
Here's a full example:
public class HelloWorld{
public static void main(String []args){
String password = "aA2";
String regexp = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,10}$";
System.out.println(password.matches(regexp));
password = "12345678";
System.out.println(password.matches(regexp));
password = "aA345678";
System.out.println(password.matches(regexp));
}
}
gives the following output:
false
false
true
The regexp matches any string, that conatins at least upper case, one lower case letter and one digit, and 6 - 10 character long.
You can find more examples of theese here. And some info about the regexps on the Wikipedia. A very good tutorial about regexps and Java can be found on Vogella. (It's a very good site, with very good tutorials, I think!) And, a handy tool to display what a regexp matches: http://www.regexper.com/
In case of the previous example, it gives you a very visually output.
Without Regexs
So, if you cannot use Regulax Expressions, I would create a function, which returns true, if the password is OK, false in any other case. Here's a small example for this function:
public static boolean passwordOk(String password){
if (password == null) return false;
if (password.length() < 6 || password.length() > 10) return false;
boolean containsUpperCase = false;
boolean containsLowerCase = false;
boolean containsDigit = false;
for(char ch: password.toCharArray()){
if(Character.isUpperCase(ch)) containsUpperCase = true;
if(Character.isLowerCase(ch)) containsLowerCase = true;
if(Character.isDigit(ch)) containsDigit = true;
}
return containsUpperCase && containsLowerCase && containsDigit;
}
The main idea thing in this solution, is a for-each loop. I create a character array from the String, and loop over the elements of it. If the current character is a digit, or uppercase, or lowercase, I set a flag, to sign, that one of the statements are true. At the beginning, all of the statements are false, and at the end I'll return the result of their sum.
In the first two lines I check, if the argument isn't null, and if it has the right length.
I hope, that after this you'll be able to solve your homework! You can call this function even with null pointers, so I would create a while loop, to run while this function do not returns true.
If it's hopeless, to solve this problem, here's the full code.
Believe me, it'll be more useful, if you try to solve this by your own, first!
You can use something like this...
if( password.matches(".*[a-zA-Z]+.*")){
System.out.println( "Has characters ");
} else {
System.out.println("Ok");
}
This is to check if the password contains a letter
Similarly you can use the regular expression ".*[0-9]+.*" to check if the password contains a digit.

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();
}

Java - See if a string contains any characters in it

The problem i'm having is when i check to see if the string contains any characters it only looks at the first character not the whole string. For instance I would like to be able to input "123abc" and the characters are recognized so it fails. I also need the string to be 11 characters long and since my program only works with 1 character it cannot go any further.
Here is my code so far:
public static int phoneNumber(int a)
{
while (invalidinput)
{
phoneNumber[a] = myScanner.nextLine();
if (phoneNumber[a].matches("[0-9+]") && phoneNumber[a].length() == 11 )
{
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
For instance why if i take away the checking to see the phoneNumber.length() it still only registers 1 character so if i enter "12345" it still fails. I can only enter "1" for the program to continue.
If someone could explain how this works to me that would be great
Your regex and if condition is wrong. Use it like this:
if ( phoneNumber[a].matches("^[0-9]{11}$") ) {
System.out.println("Continue");
invalidinput = false;
}
This will only allow phoneNumber[a] to be a 11 character long comprising only digits 0-9
The + should be outside the set, or you could specifically try to match 11 digits like this: ^[0-9]{11}$ (the ^ and $ anchor the match to the start and end of the string).
You need to put the "+" after the "]" in your regex. So, you would change it to:
phoneNumber[a].matches("[0-9]+")
Why not try using a for loop to go through each character?
Like:
public static int phoneNumber(int a)
{
while (invalidinput)
{
int x = 0;
for(int i = 0; i < phoneNumber[a].length(); i++)
{
char c = phoneNumber[a].charAt(i);
if(c.matches("[0-9+]")){
x++;
}
}
if (x == phoneNumber[a].length){
System.out.println("Continue");
invalidinput = false;
}
else
{
System.out.print("Please enter a valid phone number: ");
}
}
return 0;
}
Are the legal characters in your phone numbers 0..9 and +? If so, then you should use the regular expression [0-9+]*, which matches zero or more legal characters. (If not, you probably meant [0-9]+.) Also, you can use [0-9+]{11} instead of your explicit check for a length of 11.
The reason that your current code fails, is that String#matches() does not check whether the regular expression matches part of the string, but whether it matches all of the string. You can see this in the JavaDoc, which points you to Matcher#matches(), which "Attempts to match the entire region against the pattern."

Java Program - Email address verification using Strings and RegEx

The problem statement goes like this:
We need to create a String data type called emailId
The email ID has to be set using appropriate setter methods.
The validation rules for the email ID check have to be implemented in the main().
Conditions are:
Overall length of the email ID must be >3 and <20.
The emailId must include "#" followed by a minimum of 1 and maximum of 2 "." characters.
The substring before "#" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
The first letter of the email Id must be in Upper Case.
If all the above conditions are valid, it should display "Email ID is valid" or else, it should display an appropriate error message
This is my code:
public class EmailCheck {
String emailId;
public void setEmailId(String emailId){
this.emailId=emailId;
}
public String getEmailId(){
return emailId;
}
public static void main(String[] args) {
EmailCheck em = new EmailCheck();
em.setEmailId("CFDV#gm.a.il.com");
String email = em.getEmailId();
int length = email.length();
boolean flag1 = false;
boolean flag2 = false;
boolean flag3 = false;
boolean flag4 = false;
boolean flag5 = false;
boolean flag6 = false;
boolean flag7 = false;
int count = 0;
//Condition 1
if((length>3 && length<20)== true)
flag1 = true;
else
flag1 = false;
//Condition 2
int temp = email.length();
if(email.contains("#")){
flag2=true;
int a=email.indexOf("#");
for(int i=a;i<temp;i++){
if(email.charAt(i)=='.'){
flag3=true;
count=count+1;
}
}
if(count<1||count>2){
flag4=false;
}
else{
flag4=true;
}
}
else{
flag2 =false;
System.out.println("No # symbol present");
}
//Condition 3
if(email.matches("[A-Z a-z _]+#.*")) //Unable to get the right RegEx here!
flag5 = true;
else
flag5 = false;
//Condition4
if(Character.isUpperCase(email.charAt(0))==true)
flag6 = true;
else
flag6=false;
if(flag1==true && flag2==true && flag3==true && flag4==true && flag5==true &&flag6==true)
System.out.println("Email ID is valid");
else{
if(flag1==false)
System.out.println("Inavlid length of Email ID");
if(flag2==false||flag3==false||flag4==false)
System.out.println("Invalid Position of Special Characters");
if(flag5==false)
System.out.println("Invalid combination for username");
if(flag6==false)
System.out.println("Invalid case of first letter");
}
}
}
I'm not sure of the condition #2(the logic?) and condition #3(the RegExp part). A few of the test cases seem correct, the rest of them are wrong(owing to faulty logic in #2 and esp #3, I think.)
Please, tell me what changes have to be done here to get the right output.
Thanks!
If you insist on using regex you can use this but without validating properly you could be in for all kinds of trouble
static Pattern emailPattern = Pattern.compile("[a-zA-Z0-9[!#$%&'()*+,/\-_\.\"]]+#[a-zA-Z0-9[!#$%&'()*+,/\-_\"]]+\.[a-zA-Z0-9[!#$%&'()*+,/\-_\"\.]]+");
public static boolean isValidEmail(String email) {
Matcher m = emailPattern.matcher(email); return !m.matches();
}
Or alternatively you could use
public static boolean isValidEmailAddress(String email) {
boolean result = true;
try {
InternetAddress emailAddr = new InternetAddress(email);
emailAddr.validate();
} catch (AddressException ex) {
result = false;
}
return result;
}
Which is a core java utility which would be better...
Note that neither of these will guarentee an address is actually valid, just that it is correctly formed and so hypothetically could exist
String email_regex = "[A-Z]+[a-zA-Z_]+#\b([a-zA-Z]+.){2}\b?.[a-zA-Z]+";
String testString = "Im_an_email#email.co.uk";
Boolean b = testString.matches(email_regex);
System.out.println("String: " + testString + " :Valid = " + b);
will check for the last three constraints which you can then combine with
string.length()>3 && string.length()<20
Overall length of the email ID must be >3 and <20.
You have this part fine - a pair of length checks. Things to consider:
You don't need if (condition == true), just if (condition).
If this fails, you can stop processing the email and just display the error. The same applies for all your other error conditions.
The emailId must include "#" followed by a minimum of 1 and maximum of 2 "." characters.
Check for the # sign first and get the index. Once you have that, you can split the string. You can then split the substring on periods and count them - you want two or three.
There's probably a regex that would do this as well.
The substring before "#" must contain a combination of Upper Case, Lower Case and "_"(underscore) symbols.
You can use this approach to ensure your regex must match each part. As it stands, I believe your regex will work if there are caps, lowercase, or an underscore instead of checking for all three.
The first letter of the email Id must be in Upper Case.
Same comments as for the first part, drop the == true and short circuit the method if it fails.

Categories

Resources