alphamonkey alphamonkey - 1 year ago 48
Java Question

Issue with finding index of array item

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.

Answer Source

In your first loop where you are checking the candidate name, instead of creating a whole new object, you can do this as returnName() returns a String:

    location = i;//saves answer
    break;//gets out of loop

I do not see why you would be getting the same value for location unless you are putting in the exact same person and they happen to be at the front of the array. The logic should work, and I have used this same code myself for my classes to find an index, not with string evaluation, but the same logic. In fact, I actually did a very similar assignment around 3 weeks ago.

Also, I suggest that you set location equal to -1 if it is not found in the list as the list does not have negative indexes.