简体   繁体   English

Java不兼容类型错误

[英]Java incompatible types error

import java.util.Scanner;

public class Numbers {

    // --------------------------------------------
    // Reads in an array of integers, sorts them,
    // then prints them in sorted order.
    // --------------------------------------------
    public static void main(String[] args) {

                int[] intList;
        int size;

        Scanner scan = new Scanner(System.in);

        System.out.print("\nHow many integers do you want to sort? ");
        size = scan.nextInt();
        intList = new int[size];

        System.out.println("\nEnter the numbers...");
        for (int i = 0; i < size; i++)
            intList[i] = scan.nextInt();
        Sorting.selectionSort(intList);


        System.out.println("\nYour numbers in sorted order...");
        for (int i = 0; i < size; i++)
            System.out.print(intList[i] + " ");
        System.out.println();
    }
}

//CODE OF FIRST . // CODE OF FIRST。

public class Sorting {

    // -----------------------------------------------------------------
    // Sorts the specified array of objects using the selection
    // sort algorithm.
    // -----------------------------------------------------------------
public static void selectionSort(Comparable[] list) {

    int min;
    Comparable temp;
    for (int index = 0; index < list.length - 1; index++) {
        min = index;
    for (int scan = index + 1; scan < list.length; scan++)
        if (list[scan].compareTo(list[min]) < 0)

                    min = scan;
            // Swap the values
            temp = list[min];
            list[min] = list[index];
            list[index] = temp;
        }
    }
}

I'm not sure why this code will not work. 我不确定为什么此代码将无法正常工作。 It might be simple, but I'm not sure. 这可能很简单,但我不确定。 Here is the running of the program. 这是程序的运行。

run: 跑:

How many integers do you want to sort? 您要排序多少个整数? 1 1个

Enter the numbers... 12 输入数字... 12

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: Sorting.selectionSort at Numbers.main(Numbers.java:29) Java Result: 1 线程“主”中的异常java.lang.RuntimeException:无法编译的源代码-错误的符号类型:Numbers.main(Numbers.java:29)上的Sorting.selectionSort Java结果:1

You are attempting to convert an int[] to a Comparable[] . 您正在尝试将int[]转换为Comparable[] Normally, widening conversions are allowed for object reference types, but int[] is an array of a primitive type, so the conversion fails and a compiler error is generated. 通常,对象引用类型允许加宽转换,但是int[]是原始类型的数组,因此转换失败并生成编译器错误。

Try using an int[] as the parameter of selectionSort . 尝试使用int[]作为selectionSort的参数。 Or you can use an Integer[] for the type of intList . 或者,您可以将Integer[]用作intList的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM