简体   繁体   中英

Finding all indices for certain input

I am new with Java and also new user of this website, this is my array

    double array[]  = new double[6];

    // Initializing elements
    array[0] = 0.334;
    array[1] = 0.334;
    array[2] = 0.334;
    array[3] = 0.501;
    array[4] = 0.501;
    array[5] = 0.334;

    // Use for loop to display elements
     for (int i = 0; i < array.length; i++) 
    {
           System.out.print(array[i]);  
           System.out.print("\n");      
    }

I want to find out all indices for the value (0.334); I mean for this example it should return 4, which shows that 4 indices have this value.

                    int index=-1;
                    int i; 
                    for(i = 0; i < array.length;i++)
                        {
                            if (Input>=array[i]== ) // user input = 0.334
                               {
                                index=array[i];
                    System.out.print("Output = "+index);
                    return ;
                    }   
}
  • To find the number of occurences of a value, you can simply use a counter variable . Initialize it to 0 before the loop and increment it by 1 whenever you encounter the desired value in the array.

  • To find the list of all indices that point to the desired value, you can simply use a Set<Integer> structure, the similar principle goes here: Initialize an empty set before the loop, then add the indices to this set within the loop if they point to the value in subject. After the loop, you will have a set of all indices pointing to your certain value and set.size() (which might be used as an alternative to "counter variable") will give you the number of occurrences of that value.

First iteration:

  int count = 0;
  for (double d : array) {
    if (d == user_input) {
      count ++;
    }
  }
  return count;

Then you should take care that floating-point numbers may not compare exactly . Ie the number in memory (eg if calculated) might not be exactly the same as what the user typed (eg parsed).

  int count = 0;
  for (double d : array) {
    if (approximatelyEqual(d, user_input, 1e-6)) {
      count ++;
    }
  }
  return count;

Look here for the definition of approximatelyEqual

try this

    int count = 0;
    double input = 0.334;
    for (int i = 0; i < array.length; i++) {
        if (array[i] == input)
            ++count;
    }

    System.out.println(count);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM