我希望程序执行2件事:
这是我的代码:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
您有几个问题:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)