Find Index in Java Array: Quick Guide
To retrieve the index of a specific value in Java, you can use a for loop to iterate through an array or collection, and then check if each element is equal to the target value. If they are equal, return the index of that element.
Here is a sample code:
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int target = 3;
int index = -1;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == target) {
index = i;
break;
}
}
if (index != -1) {
System.out.println("目标数值 " + target + " 的索引为 " + index);
} else {
System.out.println("未找到目标数值 " + target);
}
}
}
In the example above, we defined an integer array called numbers and a target value called target. We then used a for loop to iterate through the numbers array and check if each element is equal to the target value. If a matching value is found, we assigned the index of that element to a variable called index and then exited the loop. Finally, we checked the value of index. If it is not equal to -1, we output the index of the target value. Otherwise, we output a message indicating that the target value was not found.