/* Requirements: Array element Lookup (finds the index of the first occurrence of the specified element in the array) analysis: A: Defines an array and initializes it statically. B: Write a function to iterate through the array, get each element in the array sequentially, and compare the known data to return the current index value if it is equal. */
View Code
classARRAYTEST5 { Public Static voidMain (string[] args) {//defines an array and initializes it statically int[] arr = {200,250,38,888,444}; //Requirements: I'm going to look for 250 the first occurrence of the index in this array intindex = GetIndex (arr,250); System.out.println ("250 The first occurrence of the index in the array is:" +index); intIndex2 = GetIndex2 (arr,250); System.out.println ("250 The first occurrence of the index in the array is:" +index2); intIndex3 = GetIndex2 (arr,2500); System.out.println ("2500 The first occurrence of the index in the array is:" +index3); }
View Code
/*
Requirements: Find the index of the first occurrence of the specified data in the array
Two clear:
return value type: int
Parameter list: int[] arr,int value
*/
Public Static intGetIndex (int[] arr,intvalue) { //iterate through the array, get each element in the array, and compare the known data for(intx=0; x<arr.length; X + +) { if(Arr[x] = =value) { //returns the current index value if it is equal. returnx; } } //The current code has a small problem//That is, if the data I am looking for does not exist in the array, then it cannot be found, and you will return the corresponding one? //so the error. //as long as the judgment, it may be false, so we have to be careful. //If the data is not found, we generally return a negative number, and return 1 return-1; } Public Static intGetIndex2 (int[] arr,intvalue) { //Define an index intindex =-1; //Modify index values if you have one for(intx=0; x<arr.length; X + +) { if(Arr[x] = =value) {Index=x; Break; } } //Back to index returnindex; }}
View Code
Array lookup element First occurrence index number