我仍然遇到了界限錯誤,我不知道爲什麼。我添加了一個print語句來查看firstList和secondList實際上是什麼,它全部搞砸了,我會在後面發佈輸出,所以也許有人可以看到發生了什麼問題。遇到陣列問題
輸出:
Names before sorting: [Justin, Butch, Mandy, Sarah, Jack, Natalie, Brent, Ashley]
[Justin, null, null, null]
[Justin, Butch, null, null]
[Justin, Butch, Mandy, null]
[Justin, Butch, Mandy, Sarah]
[Natalie, null, null, null]
[Natalie, Natalie, null, null]
[Natalie, Natalie, Natalie, null]
[Natalie, Natalie, Natalie, Natalie]
[Justin, null]
[Justin, Butch]
[Sarah, null]
[Sarah, Sarah]
[Justin]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at MergeSorter.sort(MergeSorter.java:22)
at MergeSorter.sort(MergeSorter.java:25)
at MergeSorter.sort(MergeSorter.java:25)
at MergeSorter.main(MergeSorter.java:68)
正如你所看到的,陣列全亂了,我不知道是什麼原因,請大家幫忙!
import java.util.*;
public class MergeSorter
{
public static void sort(String[] names)
{
if (names.length <= 1)
{
return;
}
String[] firstList = new String[names.length/2];
String[] secondList = new String[names.length - firstList.length];
for (int i = 0; i < firstList.length; i++)
{
firstList[i] = names[i];
System.out.println(Arrays.toString(firstList));
}
for (int i = 0; i < secondList.length; i++)
{
secondList[i] = names[firstList.length + 1];
System.out.println(Arrays.toString(secondList));
}
sort(firstList);
sort(secondList);
merge(firstList, secondList, names);
}
private static void merge(String[] firstList, String[] secondList, String[] names)
{
int first = 0;
int second = 0;
int names1 = 0;
while (first < firstList.length && second < secondList.length)
{
if (firstList[first].compareTo(secondList[second]) < 0)
{
names[names1] = firstList[first];
first++;
}
else
{
names[names1] = secondList[second];
second++;
}
names1++;
}
while(first < firstList.length)
{
names[names1] = firstList[first];
first++;
names1++;
}
while(second < secondList.length)
{
names[names1] = secondList[second];
second++;
names1++;
}
}
public static void main(String[] args)
{
String[] names = {"Justin", "Butch", "Mandy", "Sarah", "Jack", "Natalie", "Brent", "Ashley"};
System.out.println("Names before sorting: " + Arrays.toString(names));
sort(names);
System.out.println("Names after sorting: " + Arrays.toString(names));
}
}
而不是投票,你可以告訴我該怎麼改變這個帖子。我在這裏尋求幫助! – Dustin 2014-09-30 13:28:37
我沒有投票給你,但它可能是因爲這看起來像功課,你發佈了很多代碼,並基本上要求我們爲你調試。這就是說,找出數組太小的唯一最簡單的方法就是使用調試器並遍歷代碼,直到發生異常 – sunrize920 2014-09-30 13:30:36
這就是我認爲這個網站的目的!這是作業,但我已經完成了這項工作。這不像我要求的代碼,所以我可以複製和粘貼它。我無法弄清楚我不斷收到的錯誤。我在哪裏可以找到調試器?我是新來的Java。謝謝! – Dustin 2014-09-30 13:32:41