I am making a program for an assignment where I have a list of Candidates (for election), and I am practicing insertion by writing a method to find a specific person in the array and directly before it, insert a new person.
public static void insertCandidate(Candidate[]list , String find, String candidate, int votes)
{
int location = 0;
for (int i =0; i < list.length; i ++){
String temp = list[i].returnName();
if (temp.equals(candidate)){
location = i;
}
}
for (int index = list.length - 1; index > location; index --){
list[index] = list[index - 1];
}
list[location ] = new Candidate(candidate, votes);
}
}
The problem I am having is in the first part, with the for loop. I want the integer location to be the index that the chosen candidate is at, but because location is set inside the for loop, its value stays at 0 for the second for loop. As a result, the person I want to insert is inserted at the very top of the list instead of in front of the person I want.
I'm not sure how to go past this problem, so help would be appreciated.