I'm attempting to create a method to bubblesort an array of objects to be displayed to the user in alphabetical order based on the name field assigned to the object. I've been playing around with trying to figure this out for a few days now and for the life of me I can't do it. All the research I've done hasn't really helped, tried a bunch of different code and they all seem to just stop the program/give me more issues. So I figured I'd ask. This is what I'm working with now.
public static void sortName(Candidate candidate[])
{
int j;
boolean finished = true;
String temp;
while ( finished )
{
finished = false;
for (j=0;j<candidate.length-1;j++)
{
if (candidate[j].getName().compareTo(candidate[j+1].getName())>0)
{
temp = candidate[j].getName();
candidate[j].getName() = candidate[j+1].getName();
candidate[j+1].getName() = temp;
finished = true;
}
}
}
}
The lines 2nd/3rd lines in the if statement are giving me errors saying it's expecting a variable but finding a value. I suspect it's something to do with trying to access the private name field in the Candidate class through .getName(), but I'm unsure of how else to do this. Any help?
EDIT: I'm now getting an NPE error on the following line
if (candidate[j].compareTo(candidate[j+1])>0)
Here is my compareTo method from my Candidate class.
public int compareTo(Candidate candidate)
{
int candidateCompare = this.getName().compareTo(candidate.getName());
if (candidateCompare != 0)
return candidateCompare;
else{
if (this.getName().compareTo(candidate.getName()) < 0)
return -1;
if (this.getName().compareTo(candidate.getName()) > 0)
return 1;
}
return 0;
}
I do not understand why this is happening, tried researching a solution but found no help.
EDIT 2: I have the following lines in my do-while loop where I get user input for the data fields of my class. In this loop, the a new object with the data is created, and assigned to my object array named origCandidateList. Here is the code.
origCandidateList[candidateCount] = new Candidate(candidateName, candidateAge, candidateParty, candidateIssue);
candidateCount++;
I initially had the first line below the candidateCount increment, so the array was starting at 1 instead of 0, but this did not fix the issue. I still get an NPE error. The array prints out fine, so the data is going into it. But something seems to be going awry with my compareTo method.
boolean finished = false; while (!finished)is much more readable...