问题
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?
回答1:
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;
}
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/19070264/sorting-individual-elements-in-a-string-array-by-their-alphabetical-order