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

时间:2021-11-03 16:01:05

I'm new to programming/coding and have been stuck on a project in school for a few days now. The goal is to take an array full of words (each position is a different word) and sort it alphabetically. I've tried doing some research on stack overflow already, but I'm having a bit of trouble following some of the examples I've found. The class and driver (I'm using a two part setup if you will) both compile fine, no problems there. The problem occurs when I try to use alphaSort from my driver. I receive a null pointer exception for the line marked below. I've had some trouble with these exceptions in the past, so I'm sure it's something small I'm overlooking. As stated however, I'm not yet fluent enough in the java syntax to catch a small error like that.

我是编程/编码的新手,现在已经在学校停留了几天。目标是采用一个充满单词的数组(每个位置是一个不同的单词)并按字母顺序排序。我已经尝试过对堆栈溢出进行一些研究,但是在我发现的一些例子之后我遇到了一些麻烦。类和驱动程序(如果你愿意,我将使用两部分设置)编译都很好,没有问题。当我尝试从我的驱动程序使用alphaSort时,会出现此问题。我收到下面标记的行的空指针异常。我过去在这些例外中遇到了一些麻烦,所以我确信这是我忽略的小事。如上所述,我在java语法中还不够流畅,无法捕捉到这样的小错误。

I figured I should just include the entire method in-case my error is something in the beginning, before the sorting part. What I have so far (i found this on Stack overflow):

我想我应该包括整个方法,以防我的错误在开始之前,在排序部分之前。我到目前为止(我在Stack溢出时发现了这个):

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++;
    }
}

Any help would be greatly appreciated. Please be as thorough as possible in giving an answer (as i said, I'm a bit of a java newbie). Thanks :)

任何帮助将不胜感激。请尽可能详细地给出答案(正如我所说,我是一个java新手)。谢谢 :)

edit: to test for null values (which i assume are spots in my array list that are blank) i made the following method:

编辑:测试空值(我假设我的数组列表中的点是空白的)我做了以下方法:

    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++;
    }
}

the while loop never broke early, my method ran to completion.

while循环从未破坏过,我的方法跑完了。

5 个解决方案

#1


3  

You need to update the first while loop to match:

您需要更新第一个while循环以匹配:

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

You aren't copying over every index of the list to the array, which means that when it goes to check the last index, it cannot find a value (NullPointerException).

您没有将列表的每个索引复制到数组,这意味着当它去检查最后一个索引时,它找不到值(NullPointerException)。

Edit:

编辑:

Here's my full test class that works:

这是我的完整测试类:

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++]);
        }
    }

}

Output:

输出:

Bee
Dog
Pig
Test

#2


1  

Try this...

尝试这个...

 // 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);
  }
 }

#3


1  

There is an error when you are copying your List to an array. It is inserting a null at the end of the list which is causing your NullPointerException. Here is the revised version that works. Instead of looping through the List and copying each item to the array(which is buggy) I just use the standard java method that is on a List to convert the List to an array.

将List复制到阵列时出错。它在列表的末尾插入一个null,导致您的NullPointerException。这是修订后的版本。我只是使用List上的标准java方法将List转换为数组,而不是循环遍历List并将每个项复制到数组(这是错误的)。

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++;
    }
}

#4


0  

The problem is that you're adding wordList.size()-1 number of items into the array and the array size is wordList.size() which means that the last value in the array is null

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

#5


0  

For this while loop:

对于这个while循环:

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

you don't need to loop to wordList.size()-1 since you already do < instead of <=. You are stopping your loop at the second to last index and are thus not assigning a value to the last place in the array. Instead do while (count < wordList.size()) or while (count <= wordList.size()-1)

你不需要循环到wordList.size() - 1,因为你已经 <而不是<=。您在第二个到最后一个索引处停止循环,因此不会将值分配给数组中的最后一个位置。而是while(count ())或while(count>

#1


3  

You need to update the first while loop to match:

您需要更新第一个while循环以匹配:

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

You aren't copying over every index of the list to the array, which means that when it goes to check the last index, it cannot find a value (NullPointerException).

您没有将列表的每个索引复制到数组,这意味着当它去检查最后一个索引时,它找不到值(NullPointerException)。

Edit:

编辑:

Here's my full test class that works:

这是我的完整测试类:

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++]);
        }
    }

}

Output:

输出:

Bee
Dog
Pig
Test

#2


1  

Try this...

尝试这个...

 // 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);
  }
 }

#3


1  

There is an error when you are copying your List to an array. It is inserting a null at the end of the list which is causing your NullPointerException. Here is the revised version that works. Instead of looping through the List and copying each item to the array(which is buggy) I just use the standard java method that is on a List to convert the List to an array.

将List复制到阵列时出错。它在列表的末尾插入一个null,导致您的NullPointerException。这是修订后的版本。我只是使用List上的标准java方法将List转换为数组,而不是循环遍历List并将每个项复制到数组(这是错误的)。

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++;
    }
}

#4


0  

The problem is that you're adding wordList.size()-1 number of items into the array and the array size is wordList.size() which means that the last value in the array is null

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

#5


0  

For this while loop:

对于这个while循环:

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

you don't need to loop to wordList.size()-1 since you already do < instead of <=. You are stopping your loop at the second to last index and are thus not assigning a value to the last place in the array. Instead do while (count < wordList.size()) or while (count <= wordList.size()-1)

你不需要循环到wordList.size() - 1,因为你已经 <而不是<=。您在第二个到最后一个索引处停止循环,因此不会将值分配给数组中的最后一个位置。而是while(count ())或while(count>