简体   繁体   中英

Finding all Indices of a number from an Array (Java)

Say I have an array of:

int [] I = { 1, 3, 6, 3, 7,3, 9, 3};
int value = 3;

I have a for loop that tracks the amount of occurences of the value:

int counter = 0;
for(int x = 0; x < I.length; x++)
{
    if(I[x] == value)
    {
        counter++;
    }
}

I make a new array with length equal to the number of occurrences, that can store all the indices of the occurences from the original array:

int [] index = new int [counter];

for(int x = 0; x < index.length; x++)
{
    for(int i = 0; i<I.length; i++) 
    {
        if(I[i] == value){
           index[x] = i;
        }       
    }
}

However, when I print my array of indices, i just get the last index printed the amount of times counter is equal to, when I want all the indices.

for(int i = 0; i<index.length; i++)
{
    System.out.println(index[i]);
}

It just prints "7" (the last index) 3 times. How do I go about fixing this so I have an array of all indices? Thank you.

Your second for loop should not be nested; you should only increment x when you find a match. Something like,

for (int i = 0, x = 0; i < I.length; i++) {
    if (I[i] == value) {
        index[x] = i;
        x++;
    }
}

Assuming you're using Java 8+, you could have written a filter() on the range of indices in the array. Like,

int[] index = IntStream.range(0, I.length).filter(i -> I[i] == value).toArray();
System.out.println(Arrays.toString(index));

Just remove the outer for loop and store into the index array as you iterate through the original array I . The problem with your code is that, since you repeat the iterations once for each index in the index array, you end up with the last found index (7 in your case).

for(int i = 0, x = 0; i < I.length; i++)  {
    if(I[i] == value) {
        index[x++] = i;
    }       
}

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