I split a string which is a password entered by the user to only return back digits. I need to make sure those digits they entered aren't certain digits. But first, I need to take the data that comes back and turn them into an int so I can compare.
public static boolean checkPassword(String password){
String digitsRegrex = "[a-zA-Z]+";
int upPass;
String [] splitPass = password.split("[a-zA-Z]+");
for(String pass : splitPass){
try{
upPass = Integer.parseInt(pass);
}
catch (NumberFormatException e){
upPass = 0;
}
System.out.println(upPass);
}
return true;
}
When I run the program I get back the 0 (and the digits in the string password) in the catch, so the try isn't working I guess?
In your code, you set upPass
to 0 when you encounter a substring that do not contain any digits. These are empty strings. This happens when the password does not start with a digit.
You should be ignoring it as you need only digits.
Example: abcd12356zz33
- when you split using the regex [a-zA-Z]+
you get ""
, "123456"
, and "33"
. When you attempt to convert the first empty string to a number, you get a NumberFormatException
.
for(String pass : splitPass){
if (!pass.isEmpty()) {
try {
upPass = Integer.parseInt(pass);
System.out.println(upPass);
//Validate upPass for the combination of numbers
} catch (NumberFormatException e) {
throw e;
}
}
}
checkPassword("abcd12356zz33")
prints
12356
33