Reputation: 13
I'm beginner in Java. I have studied variables, statements and loops. While practicing solving problems, I am stuck at one point. The point is, while setting a password of type String
, how to implement the following rules on a password?
Upvotes: 1
Views: 58
Reputation: 16338
I would recommend you to read up on Pattern matching with regular expressions. Depending on your application, the result could look similar to this:
password.matches("[0-9a-zA-Z][\\w]{0,19}")
On a side note, I wouldn’t recommend to use only the rules you have specified to check for good passwords. For example, there is no minimum length check in your rules!
Upvotes: 0
Reputation: 718836
The password should never be more than 20 characters.
Test the string length. Read the javadoc for the String
class to find the method you need to use.
The password should start either with numbers or alphabets.
There is a method in the String
class that will give you the character at position i
in a string. Look for it.
The password should contain only "_" alphabets and numbers.
The same method can be used to look at the character at any position. Using a for
loop.
Or you can use a different kind of for
loop to iterate the characters in a String
.
I have intentionally linked to the javadoc in the Oracle Java SE (tm) documentation. Also, I have intentionally NOT linked to the specific methods ... to encourage you to explore the javadocs for yourself. I recommend you take the time to (at least) read the summary and the method / constructor index for the most commonly used classes.
Upvotes: 2