如何实施密码检查以查看是否有号码?

时间:2013-12-20 23:00:50

标签: java

如何检查密码以查看是否有号码?我有一张支票 对于长度,但密码也需要一个数字,我该如何做到这一点?我知道它与char类和循环有关,但我尝试的所有东西都让我陷入困境。任何建议都会有所帮助。

import javax.swing.JOptionPane;
public class Pasword
{
    public static void main(String[] args)
    {
        String password1 = JOptionPane.showInputDialog(null, "Please Enter A Password That Contains 6 - 10 Characters One Of Which Is A Number");
        int len = password1.length();

        while((len < 6) || (len > 10))
        {
            password1 = JOptionPane.showInputDialog(null, "! INVALID !Please Enter A Password That Contains 6 - 10 Characters One Of Which Is A Number");
            len = password1.length();
        }

        String password2 = JOptionPane.showInputDialog(null, "!PASSWORD VALIDATOR! Please Re-Enter Password");
        int len2 = password2.length();

        while((len2 < 6) || (len2 > 10))
        {
            password2 = JOptionPane.showInputDialog(null, "! INVALID !Please Re-Enter");
            len2 = password2.length();
        }
                if(password1.equals(password2))
                {
                    JOptionPane.showMessageDialog(null, "Accepted");
                }
                else
                {
                    JOptionPane.showInputDialog(null, "Passwords do not match, Pleas Re-enter");
                }

    }

}

我是java新手并且已经学到了很多东西,我只是在实现知识方面遇到了问题。 谢谢

3 个答案:

答案 0 :(得分:2)

我会使用一些正则表达式。

System.out.println("x123".matches("(.*?)\\d(.*?)"));
System.out.println("xyz".matches("(.*?)\\d(.*?)"));

答案 1 :(得分:0)

您可以遍历每个字符以检查它是否为数字:

boolean hasNumber = false;
for (int i = 0; i < len; ++i) {
    if (Character.isDigit(password1.charAt(i)) {
        hasNumber = true;
        break; // no need to keep searching
    }
}
if (!hasNumber) {
    // password1 does not contain a number
}

或者您可以使用String#matches

if (!password1.matches(".*\\d.*")) {
    // password1 does not contain a number
}

答案 2 :(得分:-1)

将字符串密码转换为int,如果有错误,那么它不是数字

将字符串转换为整数使用passwd-number = Integer.parseInt (passwd-string)