Skip to content
Advertisement

Finding all Index’s of specific Element in ArrayList (Int)

I recently got into Java Programming (Maybe it’s already getting too hard for me), and I’m doing some exercises daily to practise. One of the challenges I need to do, is to search an Element (int), and if it’s in the Array, the Index should be displayed (All index’s should be displayed if Element duplicates found in Array).

Here’s the code I have so far!


import java.util.ArrayList;
import java.util.Scanner;

public class IndexOf {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<>();
        while (true) {
            int input = Integer.valueOf(scanner.nextLine());
            if (input == -1) {
                break;
            }

            list.add(input);
        }

        System.out.println("");

        // implement here finding the indices of a number
        System.out.println("Search for?");
        int arraySize = list.size();
        int numToSearch = Integer.valueOf(scanner.nextLine());
         
        for(int i = 0; i <arraySize-1; i++){
           int pos = list.indexOf(numToSearch);
            if(list.indexOf(i)==pos){
              System.out.print(numToSearch+" is at Index: "+pos);
              
              
             
              
          }
            
          
            
        }
        
        
       
        
            
        
        
       
    }
}

So far I’ve managed to get it to print the Index of the Element I search for, but it only does it for the first correct Index it finds.

Sorry for the clunky code, haven’t yet learnt much in terms of neat code!

Advertisement

Answer

In the last loop, you were checking the equality between the index of numToSearch in list and the index of 0...arraySize-2 in list. Unless I am understanding the question incorrectly, the correct approach should be checking the equality of each array member and numToSearch. Then print out the string with the current index you are at.

This could be represented like this:

for (int i = 0; i < arraySize; i++) {
    if (list.get(i) == numToSearch) {
        System.out.println(numToSearch + " is at Index: " + i);
    }
}

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement