1

I wrote a program that consists of an ArrayList, which contains objects. Every object has a name. I want to find the index in ArrayList with the same name as i would input it with scanner. I tried the following code, but it doesnt work. q=0; while(!naziv.equals(racuni.get(q).getNaziv())) q++;

6

2 Answers 2

2

First let's format your code clearly

String name = sc.next();
int q=0;
while(q < object.size() && !name.equals(object.get(q).getName())) {
  q++;
}

Second, you must verify that q also is below the ArrayList size, cause it wouldn't make sense if you tried to access a position bigger than your Array.

Here have a sample

    ArrayList<Animal> object = new ArrayList<Animal>();
    object.add(new Animal("duck"));
    object.add(new Animal("chicken"));
    Scanner sc = new Scanner(System.in);
    String name = sc.next();
    int q = 0;
    while (q < object.size() && !name.equals(object.get(q).getName())) {
        q++;
    }
    System.out.print(q);

// Prints 0 if you write "duck"

// Prints 1 if you write "chicken"

// Prints 2 if you write "NotInArrayList"

Sign up to request clarification or add additional context in comments.

5 Comments

It prints out exactly the same thing, if I put in the String of zero index, but if I put in the name of the first index it works
@AnaPeterka Let me test it out 1 second
@AnaPeterka Compare your version to mine and figure out what's wrong in yours. Or post more of your code for us to figure out what you did wrong. Cheers :)
I figured out that when i input another name, that name replaces the name that was there before
@AnaPeterka That doesn't happen in my code. Again, try out my code, or post the rest of your code for we to analyze what's wrong in yours
0

Simple way to solve this problem in JAVA8 is by using Stream

If element is available in list, it prints the first index of element, else returns -1.

OptionalInt findFirst = IntStream.range(0, objects.size())
.filter(object-> objects.get(object).getName().equals(nextLine))
.findFirst();
System.out.println(findFirst.isPresent() ? findFirst.getAsInt() : -1);

Comments

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.