Reputation: 5
I have this program to write and have no idea how to control keyboard input:
Write a method to check whether the word entered is valid or not. Valid word should:
- Have at least 10 characters
- Start with a letter
- Contain a letter in upper case
- Contain at least 3 digits
- Contain a special character (e.g. @,$.% …etc)
- Contain a space
Upvotes: 0
Views: 561
Reputation: 728
Scanner input=new Scanner(System.in);
System.out.print("Enter Number");
//in here "input" is a Scanner name you can use any name for it as OBAMA.
int x=input.nextInt();
//here you can assigne the key board value for "x".
System.out.println(x);
then you can print it.
Upvotes: -1
Reputation: 7457
You can use this regular expression:
String REGEX = "(^[a-zA-Z](?=.*\\d{3,})(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])(?=\\s+).{10,})";
String INPUT = "your password";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(INPUT);
System.out.println("matches(): "+matcher.matches());
^[a-zA-Z] # Start with a letter
(?=.*\\d{3,}) # at least three digits must occur
(?=.*[a-z]) # a lower case letter must occur at least once
(?=.*[A-Z]) # an upper case letter must occur at least once
(?=.*[@#$%]) # a special character must occur at least once
(?=\\s+) # a space must occur at least once
.{10,} # anything, at least ten places though
$ # end-of-string
To use this, read your password (from file,swing elements,...) and call a method, say validate(String pass)
, inside validate
check it against the regex.
Upvotes: 0
Reputation: 2065
You don't need to validate it on every key stroke, wait till the user has entered the word, then validate. Assuming you are using console input:
System.out.print("Enter something > ");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
//perform validations on inputString, heres the first one:
//regex could be used instead of multiple if statements
if(inputString.length() < 10) {
System.out.println("Validation failed, word was too short");
}
else if ...
Upvotes: 2