Java不兼容类型错误
//第一个密码Java不兼容类型错误,java,type-conversion,Java,Type Conversion,//第一个密码 import java.util.Scanner; public class Numbers { // -------------------------------------------- // Reads in an array of integers, sorts them, // then prints them in sorted order. // -----------------------------------------
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();
}
}
我不知道为什么这个代码不能工作。可能很简单,但我不确定。
下面是程序的运行情况
运行:
您要排序多少个整数?一,
输入数字。。。
十二,
线程主java.lang.RuntimeException中的异常:不可编译的源代码-错误的符号类型:Sorting.selectionSort
at Numbers.mainNumbers.java:29
Java结果:1您正在尝试将int[]转换为可比较的[]。通常,对象引用类型允许进行加宽转换,但int[]是基元类型的数组,因此转换失败并生成编译器错误
尝试使用int[]作为selectionSort的参数。或者您可以使用整数[]作为intList的类型。它在顶部代码的intList上给了我一个错误。只需使用调试器。@Garret,用准确的错误消息编辑您的帖子。这段代码不起作用是什么意思:它不编译,不运行,但运行时异常会引发,运行但给出意外的输出…?您知道错误在哪一行吗?欢迎来到Java的断开类型差异的乐趣。@KenoguLabz这不是Java的代理类型差异。基元类型和引用类型不相同。True。这是它自己的独立问题。然而,存在写入协变数组的问题。保存的好处是,写入的值总是首先从数组中提取;和intList=新整数[大小];,或public static void selectionsortin[]list{。现在我必须复制该代码,并使其以字符串而不是整数读取。你知道我如何做到这一点吗?我不断遇到以下错误:
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;
}
}
}