我希望程序做两件事:
- 检查字符串(密码输入)是否同时包含字母和数字。
- 检查密码是否至少有 8 个字符。
这是我的代码:
import java.util.*;
class howstrong
{
public static void main(String ar[])
{
String password;
int i;
int c=0;
Scanner in = new Scanner(System.in);
System.out.println("ENTER PASSWORD");
password = in.next();
if (password.length() <= 8)
{
for (i = 0; i <= password.length(); i++)
{
char x = password.charAt(i);
if (Character.isLetter(x))
{
if (Character.isDigit(x))
c = 1;
}
}
if (c == 1)
System.out.println("STRONG");
else
System.out.println("NOT STRONG");
}
else
System.out.println("HAVE AT LEAST 8 CHARACTERS");
}
}
最佳答案
你有几个问题:
i <= password.length()
应该是 i < password.length()
if (password.length() <= 8)
应该是 if (password.length() >= 8)
您正在检查字符是否同时是字母和数字。
最后,我建议使用两个标志,一个检测是否有字母,另一个检测是否有数字。
把它们放在一起:
import java.util.Scanner;
class howstrong {
public static void main(final String ar[]) {
String password;
Scanner in = new Scanner(System.in);
System.out.println("ENTER PASSWORD");
password = in.next();
boolean hasLetter = false;
boolean hasDigit = false;
if (password.length() >= 8) {
for (int i = 0; i < password.length(); i++) {
char x = password.charAt(i);
if (Character.isLetter(x)) {
hasLetter = true;
}
else if (Character.isDigit(x)) {
hasDigit = true;
}
// no need to check further, break the loop
if(hasLetter && hasDigit){
break;
}
}
if (hasLetter && hasDigit) {
System.out.println("STRONG");
} else {
System.out.println("NOT STRONG");
}
} else {
System.out.println("HAVE AT LEAST 8 CHARACTERS");
}
}
}
关于java - 如何创建一个 Java 程序来检查您的密码是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37454110/