I’m trying to produce code that will search for an element starting at the end of an array and work it’s towards the beginning until i find what I am looking for. so far I have this, but it doesn’t seem to be working:
for (int i = randomList.length - 1; i > 0; i--)
{
if (randomList[i].equals(findThis))
{
System.out.println("The index of what you're looking for in the array is: " + i);
}
}
When I compile and run this, it produces the same answer as this:
for (int j = 0; j < randomList.length; j++)
{
if (randomList[j].equals(findThis))
{
System.out.println("What you're looking for is located at this index: " + j);
}
}
which is weird because it is starting at the front of the array and working its way to the end. I am grateful for all help!
You are returning the index of the found element, which is going to be the same in either direction (i.e.
array[4]will be the same regardless of how you search)If you want the count in the other direction, you could do: