I am trying to figure out how to check a String
to validate whether it had at least one letter and one number in it. I will be upfront that this is homework and I am a little confused.
There is a method isLetterOrDigit()
method that seems it would be the right approach, but I am undure as how I would implement this in my code. Here is the code I am using below:
import javax.swing.JOptionPane;
public class Password
{
public static void main(String[] args)
{
String initialPassword;
String secondaryPassword;
int initialLength;
initialPassword = JOptionPane.showInputDialog(null, "Enter Your Passowrd.");
initialLength = initialPassword.length();
JOptionPane.showMessageDialog(null, "initialLength = " + initialLength);
while (initialLength < 6 || initialLength > 10)
{
initialPassword = JOptionPane.showInputDialog(null, "Your password does not meet the length requirements. It must be at least 6 characters long but no longer than 10.");
initialLength = initialPassword.length();
}
//Needs to contain at least one letter and one digit
secondaryPassword = JOptionPane.showInputDialog(null, "Please enter your password again to verify.");
JOptionPane.showMessageDialog(null, "Initial password : " + initialPassword + "\nSecondar Password : " + secondaryPassword);
while (!secondaryPassword.equals(initialPassword))
{
secondaryPassword = JOptionPane.showInputDialog(null, "Your passwords do not match. Please enter you password again.");
}
JOptionPane.showMessageDialog(null, "The program has successfully completed.");
}
}
I want to implement a method where the comment section is using either the isDigit()
, isLetter()
, or isLetterOrDigit()
methods, but I just don't know how to do it.
Any guidance would be appreciated. Thanks in advance for the assistance.
This should work.
public boolean containsBothNumbersAndLetters(String password) {
boolean digitFound = false;
boolean letterFound = false;
for (char ch : password.toCharArray()) {
if (Character.isDigit(ch)) {
digitFound = true;
}
if (Character.isLetter(ch)) {
letterFound = true;
}
if (digitFound && letterFound) {
// as soon as we got both a digit and a letter return true
return true;
}
}
// if not true after traversing through the entire string, return false
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With