Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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^?

>Solution :

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading