0

I'm working on a program that asks user for values, and adds them onto array list until value of -1 is inserted. Then it asks, what value do you want to search for and user inserts another value. Then the program searches for all of those values in the array list, and prints out the indexes of all the found items. My program currently prints only the first item and it's index since i'm using list.indexOf(searcheditem). How do i get it to list all of the found items and not only the 1st one? Heres my code so far.

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

public class KysytynLuvunIndeksi {

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

        ArrayList<Integer> list = new ArrayList<>();
        while (true) {
            int read = Integer.parseInt(reader.nextLine());
            if (read == -1) {
                break;
            }

            list.add(read);
        }

        System.out.print("What are you looking for? ");
        int searched = Integer.parseInt(reader.nextLine());

        if (list.contains(searched)) {
            System.out.println("Value " + searched + " has index of: " + (list.indexOf(searched));
        } else {
            System.out.println("value " + searched + " is not found");
        }

    }
}

Thanks in advance!

3
  • 1
    Hello and Welcome on StackOverflow ! Why not to use the same way you fill the list; but with a second list witch would contains the values searched ? Commented Feb 21, 2018 at 11:08
  • 1
    see this question Commented Feb 21, 2018 at 11:10
  • In your question, I happened to notice that, you mentioned "the program searches for all of those values in the array list", do you infer that your program has to take more than 1 value to search? because your program does take only 1 input. Commented Feb 21, 2018 at 11:13

6 Answers 6

1

put this for loop in if condition

if (list.contains(searched)) {
     for (int index = list.indexOf(searched);index >= 0;index =list.indexOf(searched, index + 1))
    {
      System.out.println("Value " + searched + " has index of: " + index);
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

0

Iterate over the list, compare items with searched, add index to the resulting list if there's a match. Something along the lines:

List<Integer> foundIndices = new ArrayList<>();
for (int index = 0; index < list.size(); index++) {
    if (list.get(index).intValue() == searched) {
        foundIndices.add(index);
    }
}

7 Comments

Consider using a ListIterator for iterating over the input values.
@Henrik Why? (Honest question.)
Attempted a quick rewrite, and readability was not improved at all, which is often the case when people are iterating over a list and need the index. Too few people know about the ListIterator. :)
@Henrik I apreciate your effort and seriousness very much.
ListIterator can (and should) be faster if list is a non-random-access type, such as a LinkedList. Accessing all the elements of a linked list by their indices takes O(n**2) time; a ListIterator does it in O(n). For ArrayList, as in this case, it's O(n) either way, so no great loss if not using ListIterator.
|
0
public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<>();
        while (true) {
            int read = Integer.parseInt(reader.nextLine());
            if (read == -1) {
                break;
            }

            list.add(read);
        }

        System.out.print("What are you looking for? ");
        int searched = Integer.parseInt(reader.nextLine());

        for(int i=0;i<list.size();i++){
            if(list.get(i)==searched){
                System.out.println("Value " + searched + " has index of: " + (i));
            }
        }
        if (!list.contains(searched)){
            System.out.println("value " + searched + " is not found");
       }    
    }

A simple for loop would suffice.

list.contains would return the first found element in your array list.

Comments

0

A simple for loop will suffice and be faster than the combination of contains and indexOf. You may keep the loop index outside the for statement to check if nothing was found afterwards.

int i;
for (i = 0; i < list.size(); i++) {
    if (searched == list.get(i)) {
        System.out.println("Value " + searched + " has index of: " + i);
    }
}
if (i == list.size()) {
    System.out.println("value " + searched + " is not found");
}

Comments

0

I would sugger doing this if you want to use .contains() method:

ArrayList<Integer> bufflist = list.clone(); // you create a temporal back of the list to operate with the same list without destroying the data
int searched = Integer.parseInt(reader.nextLine());

while (bufflist.contains(searched)) {
    System.out.println("Value " + searched + " has index of: " + (list.indexOf(searched));
     listbuff.remove(list.indexOf(searched)); //you remove from the list so it doesn´t find it again

}

2 Comments

Several issues here. You're not actually creating a new list with bufflist, but merely referencing and changing the original. Also, inside the loop you're removing the element and then searching for it using the indexOf method. Probably should switch the two lines inside the loop.
@Henrik Fixed it!
-1

Try below code

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

public class KysytynLuvunIndeksi {

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

    ArrayList<Integer> list = new ArrayList<>();
    while (true) {
        int read = Integer.parseInt(reader.nextLine());
        if (read == -1) {
            break;
        }

        list.add(read);
    }

    System.out.print("What are you looking for? ");
    int searched = Integer.parseInt(reader.nextLine());
    for (int i : list) {
        if (i == searched) {
            System.out.println("Value " + searched + " has index of: " + (list.indexOf(searched)));
        }
    }
}

}

2 Comments

No, it'll just print the index of the first occurrence however many times the number appears in the list.
Yeah, this is basically repeating the original problem of the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.