3.15 operation of the array 5 basic lookup

Source: Internet
Author: User

/* 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. */class arraytest5 {public static void main (String[] args)  {//  defines an array, and static initialization of the int[] arr = { 200, 250, 38, 888, 444 };//  Requirement: I want to find 250 index Int index = getindex (arr, 250) in this array for the first time; System.out.println ("250 The first occurrence of the index in the array is:"  + index); Int index2 = getindex2 (arr, 250) ; System.out.println ("250 The first occurrence of the index in the array is:"  + index2); Int index3 = getindex2 (arr,  2500); SYSTEM.OUT.PRINTLN ("2500 The first occurrence of the index in the array is:"  + index3);} /* Requirements: Find the index of the first occurrence of the specified data in the array two explicit: return value type: int parameter list:int[] arr,int value*/public static int  GetIndex (Int[] arr, int value)  {//  iterates through the array, gets each element in the array, and compares the known data for  (int x  = 0; x < arr.length; x++)  {if  (arr[x] == value)  {//   Returns the current index value if it is equal. Return x;}}   The current code has a small problem//  is that if you want to find the data in the array does not exist, then can not find, find, the corresponding return?//  so error.   As long as the judgment, it may be false, so be careful.   If no data is found, a negative number is usually returned, and returns -1RETURN&NBSP;-1;} Public static int getindex2 (Int[] arr, int value)  {//  define an index int  index = -1;//  Modify the index value for  (int x = 0; x < arr.length;  x++)  {if  (Arr[x] == value)  {index = x;break;}}   return to Indexreturn index;}}


3.15 operation of the array 5 basic lookup

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.