Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java isLetterOrDigit() method, isDigit(), isLetter()

Tags:

java

methods

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.

like image 275
cdo Avatar asked Dec 03 '11 20:12

cdo


1 Answers

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;
}
like image 71
Andreas Wederbrand Avatar answered Sep 28 '22 01:09

Andreas Wederbrand