Java Reference
In-Depth Information
This call would set number to 3 for the sample array, because there are three
occurrences of 8 in the list. If you instead made the call
int number = count(list, 2);
number would be set to 0 , because there are no occurrences of 2 in the list.
Sometimes you want to find out where a value is in a list. You can accomplish this
task by writing a method that will return the index of the first occurrence of the value
in the list. Because you don't know exactly where you'll find the value, you might try
including this method in a while loop, as in the following pseudocode:
int i = 0;
while (we haven't found it yet) {
i++;
}
However, there is a simpler approach. Because you're writing a method that
returns a value, you can return the appropriate index as soon as you find a match.
That means you can use the standard traversal loop to solve this problem:
for (int i = 0; i < list.length; i++) {
if (list[i] == target) {
return i;
}
}
Remember that a return statement terminates a method, so you'll break out of
this loop as soon as the target value is found. But what if the value isn't found? What
if you traverse the entire array and find no matches? In that case, the for loop will
finish executing without ever returning a value.
There are many things you can do if the value is not found. The convention used
throughout the Java class libraries is to return the value -1 to indicate that the value is
not anywhere in the list. So you can add an extra return statement after the loop that
will be executed only when the target value is not found. Putting all this together, you
get the following method:
public static int indexOf(int[] list, int target) {
for (int i = 0; i < list.length; i++) {
if (list[i] == target) {
return i;
}
}
return -1;
}
 
Search WWH ::




Custom Search