Cup of Java
Cup of Java

Reputation: 1808

Substring out of bounds in for loop

I am writing a simple program to print out every possible password combination given a set of characters to use from. The password must be 5 characters so I am using 5 for loops to replace each one. For some reason, when I try to replace character 4, I always get an String index out of bounds -1 exception. I am not sure why this happens either.

Code

char[] charList = new char[]{'a','b','c','d','e','f'};
String password = "aaaaaa";
for (int char1 = 0; char1 < charList.length; char1++) {
    password = charList[char1] + password.substring(1, 4);
    for (int char2 = 0; char2 < charList.length; char2++) {
        password = password.substring(0) + charList[char2] + password.substring(2, 4);
        for (int char3 = 0; char3 < charList.length; char3++) {
            password = password.substring(0, 1) + charList[char3] + password.substring(3, 4);
            for (int char4 = 0; char4 < charList.length; char4++) {

                //java.lang.StringIndexOutOfBoundsException: String index out of range: -1 below
                password = password.substring(0, 2) + charList[char4] + password.substring(4);

                for (int char5 = 0; char5 < charList.length; char5++) {
                    password = password.substring(0, 3) + charList[char5];
                    System.out.println(password);
                }
            }
        }
    }
}

Upvotes: 2

Views: 623

Answers (2)

Greg Artisi
Greg Artisi

Reputation: 172

The last index of the substring method is exclusive, that means the 4th caractère is not taken.you also start at 1,that means there is only 3 characters un your substring

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53565

password = password.substring(0, 1) + charList[char3] + password.substring(3, 4); assigns a string of length 3 to password.

Then you're calling password.substring(4) which tries to access an index that doesn't exist in the string!

Upvotes: 2

Related Questions