Search for number in array and return index
I have created an array with five elements and populated it. I am trying to find a specific number within the array and output the index. If the number is not found, the output should be "False".
Sample:
Code :
// Created array
int[] iArray = {3,2,1,4,5};
//I'm looking for 5 in the array
int x1 = 5;
//loop to find 5 in the array
for (int i = 0; i < iArray.length; i++){
if (iArray[i] == x1){
int position = iArray[i];
System.out.println("Index found: " + position);
}
}
I know that the index is in fact 4, but when I run this code, it says 5. No matter what I change int x1 to, it will return the value of x1. What am I doing wrong?
Re: Search for number in array and return index
Duplicate post over at Java Forums. Already answered.
Re: Search for number in array and return index
I originally posted one this forum first. But yes, it was answered. I ended up tweaking it so that if there were multiple instances of that value, they would also be displayed. Thanks again.