数组的置换需要Size + 1在Output,Java中导致null

时间:2015-02-21 20:26:54

标签: java arrays recursion

首先,在其他任何事情之前......是的,我知道使用ArrayList会比使用数组容易得多。我明白了,但是对于这个项目,我需要学习如何使用递归来处理数组。

好的,所以在下面的代码中,我输出了数组的所有排列,但除非我将数组的大小设置为用户输入的大小+1,否则我会得到一个ArrayIndexOutOfBounds异常。这会导致数组有一个null值,该值作为空格输出,导致输出问题。

为什么要求我将大小设置为输入的大小加一?我该如何解决这个问题?提前谢谢。

package permutearray;

import java.util.Scanner;

/**
*
* @author Ra'kiir
*/
public class PermuteArray {

public static Scanner keyboard = new Scanner(System.in);

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    System.out.print("How many characters in the permute array:  ");
    int p = keyboard.nextInt();
    char[] permuteArray = new char[p+1];
    System.out.print("Enter a line of " + p + " characters:  ");
    String charString = keyboard.next();
    for (int i = 0; i < p; i++) {
        permuteArray[i] = charString.charAt(i);
    }
    permutation(permuteArray, 0, p);

} //End main method

private static void permutation(char[] permuteArray, int firstIndex, int lastIndex) {

    if (lastIndex - firstIndex == 1) {
        print(permuteArray);
        swap(firstIndex, lastIndex, permuteArray);
        print(permuteArray);
        //restore the order in string array
        swap(firstIndex, lastIndex, permuteArray);

    } else {
        //swap String at firstindex with all the next Strings in the array
        for (int i = firstIndex, j = 0; i <= lastIndex; i++, j++) {
            swap(firstIndex, firstIndex + j, permuteArray);
            //With current initial String(s) find combinations for rest of the strings 
            permutation(permuteArray, firstIndex + 1, lastIndex);
            //restore the order in string array
            swap(firstIndex, firstIndex + j, permuteArray);
        }
    }

} //End swap method

private static void swap(int firstIndex, int lastIndex, char[] permuteArray) {
    char temp = permuteArray[lastIndex];
    permuteArray[lastIndex] = permuteArray[firstIndex];
    permuteArray[firstIndex] = temp;
}

private static void print(char[] permuteArray) {
    for (int i = 0; i < permuteArray.length; i++) {
        System.out.print(permuteArray[i]);
    }
    System.out.println();
} //End print method

} //End of Main Class

0 个答案:

没有答案