0

该程序假设接受输入字符串,即密码。然后程序会检查以确保密码长度至少为 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;
    }
    }
    }
    }
4

3 回答 3

5

在你的 for 循环中,你不应该允许i等于s.length()

for (i = 0; i <= s.length(); i++)

ArrayIndexOutOfBoundsException 是在您尝试访问时引起的s[s.length()]

于 2012-10-01T02:03:29.973 回答
0

由于使用从 0 到长度的索引,此语句正在获取异常。而不是使用 0 到 < 长度。

 for (i = 0; i <= s.length(); i++){
    if (Character.isDigit(s.charAt(i))){
        numbers++;
    }
 }
于 2012-10-01T03:05:43.750 回答
0

将 for (i = 0; i <= s.length(); i++){ 替换为 for (i = 0; i < s.length(); i++){

示例:假设字符串 s = "abc"。s.length() = 3. s.charAt(0)= "a", s.charAt(1)= "b", s.charAt(2)= "c"。s.charAt(3) 不存在并抛出异常。

于 2013-07-10T07:21:31.937 回答