How to output an element that has occured or listed multiple times in an array list from a user input

Viewed 30

How to output an element (content of index) that has been repeated by the user input multiple times with out using the collections, hashmap or treemap method?

I am looking for a linear or you could say a mathematical approach rather than a ready command approach, could someone help please?

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

Scanner scanner = new Scanner(System.in);
    ArrayList<Integer> arrayList = new ArrayList<>();

    while (true) {
        int input = scanner.nextInt();
        if (input == -1) {
            break;
        }
        arrayList.add(input);
    }
    System.out.println("search for? ");
    for (int loopValue = 0; loopValue < arrayList.size(); loopValue++) {

        int input2 = scanner.nextInt();
        System.out.println(input2 + " is at index " + arrayList.indexOf(input2));
    }

/ a sample output should look similar to the following:

input user:
10
20
20
30
30
40
50
if -1 is inputted, the user will exit the loop

Number you are searching for in an array list?: the user again input the desired number 30

number 30 is at index 3
number 30 is at index 4

how can I show the indices of a frequent number just like above^?

1 Answers

If I understand your question correctly you could do:

System.out.println("search for? ");
int input2 = scanner.nextInt();
for(int i =0; i<arrayList.size();i++){
    if(arrayList.get(i)==input2){
            System.out.println(input2 + " is at index " + i); //e.g. 30 is at index 3
    }
}
Related