-1

I am working on a program,I have tried to find a way how to find all possible permutations of an array elements in Java, but it didn't work .

My code is:

public class Permutation {
    public static void main(String[] args) {
        int[] list = new int[3];
        System.out.println("enter the elements of array");
        Scanner sc = new Scanner(System.in);
        for (int i = 0; i < list.length; i++) {
            list[i] = sc.nextInt();
        }
        System.out.println(Arrays.toString(list));
        int n = list.length;
        permutation(list, n, 0);
    }
    public static void permutation(int[] list, int n, int l) {
        if (l == n - 1) {
            printArray(n, list);
            return;
        }
        for (int i = 1; i < n; i++) {
            swap(list, list[i], list[l]);
            permutation(list, n, l + 1);
            swap(list, list[i], list[l]);
        }
    }
    public static void swap(int[] list, int x, int y) {
        int temp = list[x];
        list[x] = list[y];
        list[y] = temp;
    }
    public static void printArray(int n, int[] list) {
        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i]);
        }
    }
}

This code is continuously throws an error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
    at Permutation.swap(Permutation.java:34)
    at Permutation.permutation(Permutation.java:27)
    at Permutation.permutation(Permutation.java:28)
    at Permutation.main(Permutation.java:15)

I'm not able to understand what to do in this program so that it'll produce desired output.

And what is the meaning of this error which is thrown by program??

  • Does this answer your question? [Generating permutations of an int array using java -- error](https://stackoverflow.com/questions/13218019/generating-permutations-of-an-int-array-using-java-error) – godzsa Sep 08 '20 at 08:25
  • ArrayIndexOutOfBoundsException mean exactly that. Somewhere you use an index number for an array that is greater than the max or lower than min (unlikely) index of the array. – Petronella Sep 08 '20 at 08:28
  • "Somewhere", or on line 34, to be specific. – rghome Sep 08 '20 at 08:29

1 Answers1

0

you are getting this error because you are trying to access items, not in the array try changing

i = 0 in line 25