简体   繁体   中英

Sorting individual elements in a String Array by their alphabetical order

I have to write a program that reads a list of dictionary words from a file. Subsequently, the characters of each word are put into alphabetical order and stored in the original array. (For example: Batman would become aabmnt). Now, here is what I've done so far:

public static String[] alphabeticalOrder(String[] s)
{
    //
    // Sort each individual string element by alphabetical order
    //
    for (int i = 0; i < s.length; i++)
    {
        String wordSt = s[i];
        char[] word = wordSt.toCharArray();
        Arrays.sort(word);
        s[i] = new String(word);
    }
    return s;
}

The call in main is simply: String[] alphaOrder = alphabeticalOrder(dictionary);

However, whenever I run the program, I get a NullPointerException and I can't seem to figure out why.

Changing s[i] to s[0] made me skip the error, but I need to convert all elements in the String, not just the first.

What is going wrong?

This can only happen if your string array has null elements, as Zavior commented.

Change your code to this:

public static String[] alphabeticalOrder(String[] s)
{
    //
    // Sort each individual string element by alphabetical order
    //
    for (int i = 0; i < s.length; i++)
    {
        String wordSt = s[i];
        if(wordSt == null) continue;

        char[] word = wordSt.toCharArray();
        Arrays.sort(word);
        s[i] = new String(word);
    }
    return s;
}

From what I see, NullPointerEception can happen only if one of the elements of the passed String array is null . To debug it, just do a null check before calling wordSt.toCharArray() :

if (wordSt == null) {
    System.out.println("Null encountered at index: " + i + ". Skipping this element...");
    continue;
}
char[] word = wordSt.toCharArray();

This will help you figure out what is wrong with the input, and take any necessary steps to prevent it if this is not expected.

As everyone has pointed out, you might encounter NullPointerException when wordSt is null. Yet another point where you might encounter null is when String[] s itself is null(rare but possible). So I would suggest-

public static String[] alphabeticalOrder(String[] s)
{
    if(s == null || s.length == 0) return s;
    for (int i = 0; i < s.length; i++) {
        if(s[i] != null) {
            char[] word = s[i].toCharArray();
            Arrays.sort(word);
            s[i] = new String(word);
        }
    }
    return s;
}

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM