【发布时间】:2020-12-26 14:13:51
【问题描述】:
我正在开发一个程序,我试图找到一种方法来查找 Java 中数组元素的所有可能排列,但没有成功。
我的代码是:
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]);
}
}
}
这段代码是不断的抛出错误:
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)
我无法理解在这个程序中要做什么才能产生所需的输出。
程序抛出的这个错误是什么意思?
【问题讨论】:
-
ArrayIndexOutOfBoundsException 就是这个意思。在某个地方,您使用的索引号大于数组的最大值或小于数组的最小值(不太可能)。
-
“某处”,具体来说是在第 34 行。
标签: java arrays algorithm permutation