该程序假设接受输入字符串,即密码。然后程序会检查以确保密码长度至少为 8 个字符,至少包含 2 位数字,并且仅包含字母和数字。我似乎无法找到正确的方法来计算至少 2 位数字,尽管据我所知,这种方法应该有效。
这是我在线程“main”java.lang.StringIndexOutOfBoundsException 中得到异常的错误:String index out of range: 10 at java.lang.String.charAt(String.java:658) at Password.main(Password.java:35 )
import java.util.*;
public class Password{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String s;
int numbers = 0;
System.out.println("Enter a password (Must contain only letters and numbers, ");
System.out.print("minimum of 8 characters with atleast two numbers): ");
s = input.nextLine();
while(1==1){
if (s.length() < 8){
System.out.println("Password is too short");
System.out.println("Enter correctly formatted password");
s = input.nextLine();
continue;
}
if (s.matches("^[a-zA-Z0-9_]+$")){
}
else{
System.out.println("Password may only contain Letters and Digits");
System.out.println("Enter correctly formatted password");
s = input.nextLine();
continue;
}
int i;
for (i = 0; i <= s.length(); i++){
if (Character.isDigit(s.charAt(i))){
numbers++;
}
}
if (numbers < 2){
System.out.println("Password must contain atleast 2 digits");
System.out.println("Enter correctly formatted password");
s = input.nextLine();
continue;
}
break;
}
while (0==0){
System.out.println("Reenter Password to see if it matches");
String a = input.nextLine();
if (s.equals(a)){
System.out.println("Password matches!");
break;
}
else{
System.out.println("Password does not match");
continue;
}
}
}
}