如何在Java中按字母顺序对字符串数组进行排序?

3
我是一个新手程序员,正在学校的项目中卡了几天。目标是将一个包含单词的数组(每个位置都是不同的单词)按字母顺序排序。我已经在stackoverflow上做了一些研究,但是我有点难以理解我找到的一些示例。类和驱动程序(如果你愿意,我正在使用两部分设置)都可以编译,没有问题。问题出现在我尝试从我的驱动程序中使用alphaSort时。我在下面标记的行收到一个空指针异常。过去我也遇到过这些异常,所以我确定这是我忽略了一些小问题。但正如我所说,我还不够熟练,无法捕捉这样的小错误。
我想我应该把整个方法都包括进来,以防我的错误发生在排序部分之前。到目前为止,我找到了以下代码(我在Stack overflow上找到了它)。
public void alphaSort()
{
    String alphaList[] = new String[wordList.size()];
    int count=0;
    //puts wordList into alphaList for easier sorting
    while(count<wordList.size()-1)
    {
        alphaList[count]=wordList.get(count);
        count++;
    }
    int shortestStringIndex;
    //sort begins here
    for(int j=0; j<alphaList.length -1; j++)
    {
        shortestStringIndex = j;
        for(int i=j+1; i<alphaList.length; i++)
        {
            if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim())<0) //null pointer exception points here
            {
                shortestStringIndex = i;
            }
        }
        if(shortestStringIndex !=j)
        {
            String temp = alphaList[j];
            alphaList[j] = alphaList[shortestStringIndex];
            alphaList[shortestStringIndex]=temp;
        }
    }
    //prints out results
    count=0;
    while(count<alphaList.length)
    {
        System.out.println(alphaList[count]);
        alphaOut.print(alphaList[count]);
        count++;
    }
}

非常感谢您的帮助。请在回答时尽可能详细(因为我是Java新手)。谢谢:)
编辑:为了测试空值(我假设是数组列表中的空白点),我编写了以下方法:
    public void isNull()
{
    int count=0;
    while(count<wordList.size()-1)
    {
        if((wordList.get(count)).equals(""))
        {
            System.out.println("null");
            break;
        }
        else
        {
            System.out.println("nothing yet");
        }
        count++;
    }
}

while循环从未提前退出,我的方法运行完成。


有趣的学习方式...http://www.sorting-algorithms.com/ - AJ X.
在调试这些问题时非常有用的一件事是堆栈跟踪,当错误发生时,您可以在控制台中得到它。通常会显示“NullPointerException”,并给出错误发生的行号。如果您查看代码和它提到的行号,那里通常只有一个或两个变量在起作用,然后您可以推断出哪个变量为空,以及为什么会发生这种情况。 - nbrooks
一个空字符串并不等同于 null。一个 null 引用是指一个变量根本不包含任何字符串值。例如:String a = null。要测试 isNull,只需简单地说 if (string == null) - nbrooks
谢谢。我不知道这个。 - satincorvo
5个回答

3
您需要更新第一个while循环以匹配:
while(count < wordList.size()) {
            alphaList[count] = wordList.get(count);
            count++;
        }

你没有将列表的每个索引都复制到数组中,这意味着当它尝试检查最后一个索引时,找不到任何值(NullPointerException)。
编辑:
这是我完整的测试类,它可以正常工作:
import java.util.ArrayList;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    private ArrayList<String> wordList = new ArrayList<String>();

    public Test() {
        wordList.add("Test");
        wordList.add("Bee");
        wordList.add("Pig");
        wordList.add("Dog");
        alphaSort();
    }

    public void alphaSort() {
        String[] alphaList = new String[wordList.size()];
        int count = 0;
        while(count < wordList.size()) {
            alphaList[count] = wordList.get(count);
            count++;
        }
        int shortestStringIndex;
        for(int j = 0; j < alphaList.length - 1; j++) {
            shortestStringIndex = j;
            for(int i = j + 1; i < alphaList.length; i++) {
                if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim()) < 0) {
                    shortestStringIndex = i;
                }
            }
            if(shortestStringIndex != j) {
                String temp = alphaList[j];
                alphaList[j] = alphaList[shortestStringIndex];
                alphaList[shortestStringIndex]= temp;
            }
        }
        count = 0;
        while(count < alphaList.length) {
            System.out.println(alphaList[count++]);
        }
    }

}

输出:

Bee
Dog
Pig
Test

这个有效。我仍然有错误,但我只测试了你的输入(test,bee等),它运行得很好。这让我认为是我的数组列表中的空值。我明天会解决这个问题。你有没有什么简单的方法可以从数组列表中删除空值? - satincorvo
1
在运行alphaSort之前,请执行以下操作:wordList.removeAll(Collections.singleton(null)); @corvonik - Sean Perkins
看起来完美。我需要导入什么才能使用集合框架?编译后出现错误:无法找到符号。 - satincorvo
import java.util.Collections; - Sean Perkins

1
尝试这个...
 // sorting array
 if(wordList.size()>0){
   String alphaList[] = new String[wordList.size()];
   //convert list to String array
   alphaList= wordList.toArray(alphaList);
   //sorting
   Arrays.sort(alphaList);
 }

 ........

// let us print all the elements available in wordList
 if(wordList.size()>0){
   for (String word: alphaList) {
   System.out.println("word= " + word);
  }
 }

1

在将列表复制到数组时出现错误。它在列表末尾插入了一个 null,导致 NullPointerException。这是已经修订过的版本,可以正常工作。我不再使用循环遍历列表并将每个项复制到数组中(这是有问题的),而是使用标准的 Java 方法将列表转换为数组。

public static void alphaSort()
{
    String alphaList[] = wordList.toArray(new String[]{});
    int shortestStringIndex;
    //sort begins here
    for(int j=0; j<alphaList.length -1; j++)
    {
        shortestStringIndex = j;
        for(int i=j+1; i<alphaList.length; i++)
        {
            if(alphaList[i].trim().compareTo(alphaList[shortestStringIndex].trim())<0) //null pointer exception points here
            {
                shortestStringIndex = i;
            }
        }
        if(shortestStringIndex !=j)
        {
            String temp = alphaList[j];
            alphaList[j] = alphaList[shortestStringIndex];
            alphaList[shortestStringIndex]=temp;
        }
    }
    //prints out results
    int count=0;
    while(count<alphaList.length)
    {
        System.out.println(alphaList[count]);
        alphaOut.print(alphaList[count]);
        count++;
    }
}

尝试了这个。我喜欢它使传输更容易,但我仍然遇到了空指针异常。 - satincorvo
确保您没有将空值插入到wordList中。由于您没有发布完整的代码,因此我无法验证该方法之外的wordList发生了什么。 - Josh Chappelle
我把你的代码复制进去运行了,但是我不得不创建自己的wordList。当我这样做时,它就可以工作了。如果你认为有帮助的话,我可以发布我的完整代码。 - Josh Chappelle
这是我的单词列表。现在正在努力删除空值。感谢你的所有帮助,伙计。 - satincorvo
没问题。如果我的回答帮助您解决了问题,请不要忘记接受我的答案。谢谢! - Josh Chappelle

0

对于这个 while 循环:

while (count<wordList.size()-1)
{
    alphaList[count]=wordList.get(count);
    count++;
}

你不需要循环到 wordList.size()-1,因为你已经使用了 < 而不是 <=。你的循环在倒数第二个索引处停止,因此没有给数组中的最后一个位置赋值。相反,应该使用 while (count < wordList.size()) 或者 while (count <= wordList.size()-1)


我早就认为这是问题所在了。再试一次以进行双重检查,但没有那么幸运 :/ - satincorvo

0
问题在于您正在将 wordList.size()-1 个项目添加到数组中,而数组大小为 wordList.size(),这意味着数组中的最后一个值是 null

我一开始就以为这是问题所在。再试一次只是为了再确认一下。可惜没有这么幸运 :/ - satincorvo
你确定wordList中没有空值吗? - A.Grandt
@corvonik 如果这不是唯一的问题,可能 wordList 列表包含 null 值。 - Titus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接