За границами.Попытка получить доступ к индексу 98 без видимой причины - PullRequest
0 голосов
/ 10 декабря 2011

В качестве вызова моим начинающим программистским навыкам я подумал, что было бы интересно посмотреть, смогу ли я написать простой пароль для перебора.Итак, я начал писать приложение, которое генерирует, учитывая значение длины строки, каждую буквенно-цифровую перестановку, которую он может выполнить.Однако, поскольку я новичок в программировании, у меня возникли проблемы.

Во-первых, несмотря на то, что я импортировал java.lang.Math, я получаю сообщения об ошибках, которые не могут найти символ: pow.Мне удалось это исправить, написав полностью java.lang.Math.pow ();когда я использую функцию вместо этого, но почему это работает, а импорт - не для меня.

Во-вторых, независимо от длины ввода, после ввода я получаю ошибку времени выполнения:

aaException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 98
at combination.main(combination.java:53)

Что говорит о том, что в строке 53:

current[j] = alphanum[((int)current[j])+1];

Я, очевидно, пытаюсь получить доступ к индексу 98 либо в [current], либо в alphanum []?Что, насколько я понимаю, не должно происходить ...

Я довольно озадачен этим развитием.В любом случае, вот мой код:

//48-57 65-90 97-122

import java.util.Scanner;
import java.lang.Math;

public class combination {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        //Alphanum will be an array of chars: the lowercase letters of the alphabet, the uppercase, and the numbers 0-9.
        char[] alphanum = new char[62];

        //Set indexes 0-25 as lowercase a-z, and indexes 26-51 as uppercase A-Z, using ascii conversion.
        for (int i=0; i<26; i++) {
            alphanum[i] = (char)(i+97);
            alphanum[i+26] = (char)(i+65);
        }

        //Set indexes 51-61 as 0-9.
        for (int i=0; i<10; i++) {
            alphanum[i+52] = (char)(i+48);
        }

        //Take in variable for length.
        System.out.print("Enter length: ");
        int length = in.nextInt();

        //Current will be an array of chars: it will hold the current permutation being generated.
        char[] current = new char[length];

        //Set all indexes in current to "a" by default, and print this string as the first permutation.
        for (int i=0; i<length; i++) {
            current[i] = alphanum[0];
            System.out.print(current[i]);
        }

        //power will be a temporary double, used to calculate the number of iterations needed, as the pow function works with doubles.
        double power = (java.lang.Math.pow(62.00, ((double)length)));

        //Convert power to an integer, iterations, and subtract 1 because one iteration was already printed previously.
        int iterations = ((int)power)-1;

        /*The loop works like this. The rightmost char is checked, and if it is the maximum value of the idex
        it is reverted to idex 0 again and the index value of the char to the left of it is increased by 1,
        if it is not the maximum then it is just increased by 1. This is iterated the right number of times such
        that every alphanumeric permutation of that length has been returned.*/
        for (int i=0; i<iterations; i++) {
            for (int j=(length-1); j>=0; j--) {
                if ((j!=0) && (((int)current[j])==122)) {
                    current[j] = alphanum[0];
                    current[j-1] = alphanum[((int)current[j-1])+1];
                } else if (j!=0) {
                    current[j] = alphanum[((int)current[j])+1];
                } else {
                    System.out.println("This has looped too many times. Something is wrong.");
                }
            }

            //At the end of each iteration, print the string.
            for (int l=0; l<length; l++) {
                System.out.print(current[l]);
            }
        }
    }
}

Я был бы очень благодарен за любую помощь или понимание, которое вы могли бы предложить.^ _ ^

Ответы [ 2 ]

4 голосов
/ 10 декабря 2011

Ваш массив alphanum имеет размер 62, а значение ((int)current[j-1])+1 равно 98 (> 62).

Значение int для символа 'a' равно 97.

1 голос
/ 10 декабря 2011

Я, очевидно, пытаюсь получить доступ к индексу 98 в текущем [] или алфавитном []?Что, насколько я вижу, не должно происходить ...

Это вполне возможно, поскольку вы пытаетесь получить доступ к элементу в алфавите по определенному индексу, где индекс получен из содержимоговашего текущего массива.Я предлагаю вам распечатать содержимое этих массивов на разных этапах, и вы быстро обнаружите, где именно ваш код ведет себя не так, как вы думали

current[j] = alphanum[((int)current[j])+1];

Здесь вы пытаетесь получить доступ к

int index = ((int)current[j])+1;
current[j] = alphanum[index];

где индекс кажется 98

...