字符串索引错误

时间:2012-04-28 00:44:15

标签: java error-handling stringbuilder

我一直收到错误消息,指出我的String索引超出了String.charAt,PasswordGenerator.matchCharAt和Driver.main的范围。我不知道究竟是什么意思。此外,我的字符不会附加到我已经实例化的stringbuilder类中的一行。我想知道是否可能是由String索引错误或是否是我的错误引起的。

public class Driver {

    public static void main(String[] args) {
        int length=0;
        int MaxNumber=100;
        StringBuilder password = new StringBuilder();

        do {
            if (PasswordGenerator.matchLength (length))
                System.out.println("The length of the character is " + length);
            length++;                                     // length is randomly picked
        } while (length < MaxNumber );   // or <100

        int index = 0;
        char f = 0;

        for (int d = 0; d < 127 || ; d++) {
            if  (PasswordGenerator.matchCharAt(f, index))
                d = (char) index;
            char aChar = (char)d;
            password.append(aChar);
            System.out.println("Password is: " + aChar);
            index++;

        }
    }
}

1 个答案:

答案 0 :(得分:2)

您收到错误,因为idx将在0到127之间变化。PasswordGenerator的密码可能不会那么长。例如,在询问索引57是否匹配之前,您必须询问57是否小于密码的长度。

所以你的任务是猜测发生器保存的密码?然后你应该这样做:

Get to know the length of the password.
For each index from 0 upto but excluding the length:
    Guess the character at that index.