在使用Java时,我被告知要从课本中复制selectionSort方法并使用它。在使用它的过程中,程序中出现了问题,告诉我我的参数selectionSor特(int[],int(不兼容,但我认为T应该是许多不同的参数。为什么不起作用?(P.S.忽略对用户输入的请求,这是我添加到任务中的一点额外工作,如果我能使该方法工作,我可以添加用户输入((Double P.S.,我制作了另一个方法,printArray来清除Array的蛛网,但没有将该方法附加到下面的代码中(。
我从Eclipse得到以下消息:方法selectionSort(T[],int(在类型Program15_4中适用于自变量(int[],int(
当终止程序时,我收到以下错误消息:线程中出现异常";主";java.lang.Error:未解决的编译问题:Program15_4 类型的方法selectionSort(int[],int(未定义
at Program15_4.main(Program15_4.java:25)
import java.util.*;
public class Program15_4 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] input = new int[10];
System.out.println("Please enter 10 numbers");
for (int index = 0; index < input.length; index++) {
input[index] = in.nextInt();
}
int [] n = { 4, 8, 12, 14, 20, 24 };
System.out.println(selectionSort(n, n.length));
printArray(input);
}
//enter code here
public static <T extends Comparable <? super T>>
void selectionSort(T[] a, int n)
{
for (int index = 0; index <n -1; index++)
{
int indexOfNextSmallest = getIndexOfSmallest (a, index, n-1);
swap (a, index, indexOfNextSmallest);
}
}
private static <T extends Comparable<? super T>>
int getIndexOfSmallest(T[] a, int first, int last)
{
T min = a[first];
int indexOfMin = first;
for (int index = first +1; index <= last; index++)
{
if (a[index].compareTo(min) < 0)
{
min = a[index];
indexOfMin = index;
}
}
return indexOfMin;
}
private static void swap(Object [] a, int i, int j)
{
Object temp = a[i];
a[i] = a[j];
a[j] = temp;
}
解决方案:使用上面的selectionSort((方法
public class Program15_4 {
public static void main(String[] args) {
Integer [] n = { 20, 14, 12, 24, 2, 21 };
selectionSort(n, n.length);
System.out.println(Arrays.toString(n));
}
几个建议:
-
将数组
n
声明为Integer
的数组,而不是int
。在Java中,int
是一个基元类型,不能用于像T
这样的泛型类型变量。此外,不要按排序顺序初始化数组中的数字,因为您想测试排序代码是否有效。所以,你可以这样声明你的数组:Integer[] n = { 20, 14, 12, 24, 2, 8, 4 };
-
您的
selectionSort
函数是void,这意味着它不返回任何内容。因此,您不能使用System.out.println
来打印它的返回值,因为它没有返回值。所以,只需调用函数:selectionSort(n, n.length);
-
您可以使用
Arrays.toString
方法打印数组,如下所示:System.out.println(Arrays.toString(n));