【发布时间】:2017-02-07 07:06:39
【问题描述】:
目前难以使用选择排序和冒泡排序代码。 选择排序用于按升序排序学生ID,而冒泡排序用于按升序排序姓氏。程序编译但在选择 10 或 11 时崩溃。
我的数组声明如下:
student[] list = new student[100]; //my array
这是我用于选择排序和冒泡排序的代码。我正在使用带有方法的数组:
if (choice == 10) { // Dissplay the sorted array by student id
SortArrayBySelection(list);
System.out.println("Sorted studentid are:");
for (int i =0; i< studentNumber; i++)
{
System.out.println(list[i]);
}
}
if (choice == 11){ // Display the sorted array by family name
BubbleSort(list);
System.out.println("The sorted names are:");
for(int i = 0; i < studentNumber; i++)
{
System.out.println(list[i].Getfamilyname());
}
}
} while (choice != 1);
}
public static void SortArrayBySelection(student[] arrayToSort){ // Function to sort out the array on sutdentid
for(int i = 0; i < arrayToSort.length-1; ++i)
{
int minIndex = i;
int studentid3 = arrayToSort[i].Getstudentid();
int studentid2 = arrayToSort[minIndex].Getstudentid();
for(int j = i + 1; j <arrayToSort.length; ++j)
{
int studentid1 = arrayToSort[j].Getstudentid();
if(studentid1 < studentid2)
{
minIndex = j;
}
}
int temp = studentid3;
studentid3 = studentid2;
studentid2 = temp;
}
}
public static void BubbleSort(student[] arraySort){
String t;
for(int i = 0; i<arraySort.length; i++){
for(int j=0; j<arraySort.length-1;j++){
String str1 = arraySort[j].Getfamilyname();
String str2 = arraySort[j+1].Getfamilyname();
if(str1.compareTo(str2)<0){
t = str1;
str1 = str2;
str2 = t;
}
}
}
}
任何建议将不胜感激!谢谢 错误:
Exception in thread "main" java.lang.NullPointerException
at client.Client.SortArrayBySelection(Client.java:270)
at client.Client.main(Client.java:232)
Exception in thread "main" java.lang.NullPointerException
at client.Client.BubbleSort(Client.java:288)
at client.Client.main(Client.java:246)
【问题讨论】:
-
我猜是抛出了一些异常,是哪一个?
-
你得到的错误是什么,
The program compiles but crashes upon choosing choice 10 or 11它没有抛出任何错误?发布那个错误日志? -
错误:在 client.Client.SortArrayBySelection(Client.java:270) 在 client.Client.main(Client.java:232) 的线程“main”中出现异常 java.lang.NullPointerException 在线程中出现异常在 client.Client.BubbleSort(Client.java:288) 在 client.Client.main(Client.java:246) 处的“main”java.lang.NullPointerException
-
有什么建议吗?错误代码已上...
-
是您的错误显示行号,我们在您的代码中看不到行号,所以它们根本没有帮助,但可能您的数组没有完全填充。
标签: java arrays sorting bubble-sort selection-sort