确保一个单词是一个特定的长度

时间:2014-11-20 19:43:35

标签: java string

我是新来的,我正在制作一个程序,允许一个人注册某些东西。它接受用户名,将其与其他人进行比较,如果它是唯一的,则允许它。但是,当他们输入密码时,我不知道如何确保该字数超过8位。我需要能够将密码与某些东西进行比较,并且只有在密码超过8位时才允许密码。谢谢!

4 个答案:

答案 0 :(得分:3)

您应该将密码接受为String类型。然后使用String.equals(String otherWord)方法将其与其他字符串进行比较,并使用String.length()方法检查其长度,如下所示: -

Scanner s=new Scanner(System.in);
boolean flag=true;
String pwd="";
while(flag) {
pwd=s.nextLine();
if(pwd.length()>8 && pwd.equals("IntendedWord"))
// set flag=false AND then continue your intended action...
else
System.out.println("Please try again");
}

答案 1 :(得分:2)

您要查找的方法是String.length()

使用类似:

if (password.length() > 8) {
    // password is long enough
}

答案 2 :(得分:2)

尝试这样的事情:

 // Previous code gets the value for the field and stores it in String pass

 if ( pass.length() > 8 )
 {
    // it is valid. Hash and save
 }
 else
 {
    // Not valid. Let user know and ask for reentry.
 }

 //etc.

您可以将此检查和其他检查置于验证功能中,并在存储之前调用它。

如果您还有其他需要,请告诉我。

另外,有两件事需要了解Stack Overflow作为礼貌。请在发布前搜索与您类似的问题。第二,在发布时提供更多信息,这样人们就不必猜测你想要/需要什么。

答案 3 :(得分:1)

你可以使用像

这样的东西
if(password.length() > 8)
{
//some logic
}

也就是说,考虑到您将密码作为字符串值。

相关问题