可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I need to organize an array of Strings alphabetically. In theory, the first letter of each word is capitalized (although not necessarily, because one can't always trust users). I have tried Arrays.sort()
and it won't run the program. I have tried using compareTo()
, and while it runs the program, when it gets to that section of code, I get this error:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(Unknown Source)
at NameandAge.printNameOrder(NameandAge.java:431)
at NameandAge.print(NameandAge.java:350)
at NameandAge.main(NameandAge.java:116)
Literally everything I can find on this subject gives me one of those two solutions. Any other suggestions?
(For the record, the code currently reads: )
while(!done)
{
done=true;
for(int i=0;i<organizedNames.length-1;i++)
{
if(!(organizednames[i]==null))
{
String name1=organizedNames[i]; String name2=organizedNames[i+1];
if(name1!=null&&name2!=null)
{
int num=name1.compareTo(name2);
if(num>0)
{
temp=organizedNames[i]; //temp is a String that was declared earlier
organizedNames[i]=organizedNames[i+1];
organizedNames[i+1]=temp;
done=false
}
}
}
}
}
EDIT: Tried checking to make sure name1 and name2 weren't null
. It works now, but this is the output:
Joe
Bill
Bob
Smith
Rodney
James
Philip
Lillian
Charlie
Angel
Carol
Noah
I added the whole section of code now(minus the while loop, of course). This is basically the exact solution I found, and the first one to give me any output at all. What am I doing wrong?
EDIT (again): This is the code that calls the sort.
String[]organizedNames=new String[names.length];
organizedNames=sortNames(organizedNames);
And the code for the sort itself is basically what's in the answer below.
回答1:
Assuming you are running some variation of the bubble sort algorithm, and that you have not sanitised you input array for null strings, the problem is likely that organizedNames[i]
is null.
If this is the case you need to decide if you want to remove null items, or list them at the end of the array. If the latter is true, prior to doing a comparison, check if name1 == null || name2 == null
if so, set num to -1, this will put all the null items in an array in one place.
To answer your secondary question, try this:
boolean done = false;
while(done == false){
done = true;
for(int i=0;i<organizedNames.length-1;i++)
{
int num = 0;
if(organizedNames[i] != null && organizedNames[i + 1] != null)
{
String name1=organizedNames[i]; String name2=organizedNames[i+1];
num=name1.compareTo(name2);
}
else if(organizedNames[i] == null && organizedNames[i + 1] == null){
num = 0;
}
else if(organizedNames[i] == null){
num = 1;
}
else {
num = -1;
}
if(num>0)
{
String temp=organizedNames[i];
organizedNames[i]=organizedNames[i+1];
organizedNames[i+1]=temp;
done=false;
}
}
}
回答2:
You've gotten yourself into a right mess here! What you've been trying to do is to implement your own sort algorithm from the ground up, without understanding why the original version wasn't working. It didn't work ... for the same reason the original version didn't work.
If I am reading the evidence correctly, the root cause of your problems is the null
values in your input array. There are three simple ways to deal with this:
Get rid of the null
values by creating a new (smaller) array with the nulls eliminated.
Replace the null
values with some value (e.g. an empty String
) that can be safely compared without causing an NPE.
Implement a Comparator
that is tolerant of null
s. For example, if we wanted to make null
sort after non-null strings ...
public class MyComparator implements Comparator<String> {
public int compare(String s1, String s2) {
if (s1 == null) {
return (s2 == null) ? 0 : +1;
} else {
return (s2 == null) ? -1 : s1.compareTo(s2);
}
}
}
String[] array = ...
Arrays.sort(array, new MyComparator());
If you are interested in why your code in the Question isn't sorting properly, it is because of your strategy for dealing with null
. Basically, the code (as written) compares successive pairs of array entries, swapping them if they are out of order. When it makes a pass through the array that doesn't find anything to swap, it stops. The problem is that if either of the elements it is comparing is null
, it doesn't compare them. So if you have a null
in the array, any non-null elements before the null
cannot be compared with any non-null elements after the null
.
回答3:
Using collections we can do like this..
SortedSet<String> set = new TreeSet<String>();
String[] s = { "this", "will", "be", "sorted", "without", "ba", "any", "sort()", "function", "or","comparator" };
for (int i = 0; i < s.length; i++)
{
set.add(s[i]);
}
for (Object element : set) {
System.out.println(element.toString());
}
回答4:
Firstly, String class is immutable, i.e. no matter how you sort it or arrange it. It will never change the insertion order inside itself.
The reason for this is because when you create a String class object, a memory is allocated inside the String Constant/Literal Pool, which maybe be used by many other programs/methods that are concurrently running on the same JRE.
class Test{
public static void main(String args[]){
String s="Jake";
s.concat(" Paul");//concat() method appends the string at the end
System.out.println(s);//will print Jake because strings are immutable objects
}
}
Therefore, try the usual sorting algorithm wont work here.
You can how ever use StringBuilder instead of String. Since, StringBuilder is mutable, your manual sorting algorithms should work on them.
Hope this helps.
回答5:
Use this Code which not use any Predefined Array.Sort()
and compareTo()
method
sortStringArray(new String[]{"Henry Bernard",
"Cherish Davidson",
"Joshua Norris",
"Eleanor Kelley",
"Jaslyn Schneider",
"Holly Herman",
"Willie Strong",
"Eliana Villa",
"Lennon Odom",
"Monica Velasquez",
"Salvatore Levy",
"Taliyah Bruce"});
public static void sortStringArray(String[] array) {
for (int i = 0; i <= array.length - 1; i++) {
for (int j = 1; j < array.length - i; j++) { //Apply the bubble Sort
if (CompareString(array[j - 1], array[j]) == 1) { //Pass the two adjacent string for comparing
String temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
for (int i = 0; i <= array.length - 1; i++) {
System.out.println(array[i]);
}
}
private static int CompareString(String first, String second) {
int len;
if (first.length() >= second.length()) //we need to take the smallest string length
len = second.length();
else
len = first.length();
for (int i = 0; i <= len; i++) {
if (first.charAt(i) > second.charAt(i)) //Suppose the first string letters is greater then return 1;
return 1;
else if (first.charAt(i) < second.charAt(i)) //if second string letter is greater then return -1;
return -1;
}
return 0; //if both the equal then return 0
}