Abby :
I would need to find if the user input for password contains only 1 digit and I am having trouble what the if statement would be.
I currently only have:
import java.util.Scanner;
public static boolean onlyOneDigit (String password) {
if ( ........ ) {
System.out.print("Password requirement not met");
return true;
} else {
return false;
}
}
public static void main(String[] args) {
do {
System.out.print("Enter a password");
String password = input.next();
} while (onlyOneDigit(password));
{
System.out.print("Password updated");
}
}
WJS :
Try this. Single digit in password vs no digit or more than one in password.
for (String pw : new String[]{"with1digit", "withtwo22digits","withNodigits",
"with2scatt2reddi3gits"}) {
boolean m = pw.matches("[^\\d]*\\d[^\\d]*");
System.out.println(m + " : " + pw);
}
Prints the following:
true : with1digit
false : withtwo22digits
false : withNodigits
false : with2scatt2reddi3gits
Example usage.
if (onlyOneDigit(password)) {
// it's good
} else {
// warn user
}
public static boolean onlyOneDigit(String pw) {
return pw.matches("[^\\d]*\\d[^\\d]*");
}
And her is another way
public static boolean onlyOneDigit(String pw) {
// get rid of the first digit
String save =pw.replaceFirst("\\d","");
// replace the next digit with a #
save = save.replaceFirst("\\d", "#");
// if save contains # it had more than 1 digit
// or if save equals the original password
// then there were no digits.
return !(save.equals(pw) || save.contains("#"));
}
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=300245&siteId=1