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++;
-
1Because the array list contains two objects. The one with index 0 and another with index onejeprubio– jeprubio2018-01-03 15:04:03 +00:00Commented Jan 3, 2018 at 15:04
-
Check q < object.size() in the while conditionjeprubio– jeprubio2018-01-03 15:05:01 +00:00Commented Jan 3, 2018 at 15:05
-
2The exception message tells you exactly what's wrong: You're trying to access Index 2 and the list has only size 2! (Index 0 and 1 in the list)ParkerHalo– ParkerHalo2018-01-03 15:05:06 +00:00Commented Jan 3, 2018 at 15:05
-
3Possible duplicate of What is a debugger and how can it help me diagnose problems?Turing85– Turing852018-01-03 15:07:33 +00:00Commented Jan 3, 2018 at 15:07
-
1Possible duplicate of What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?jeprubio– jeprubio2018-01-03 15:11:05 +00:00Commented Jan 3, 2018 at 15:11
|
Show 1 more comment
2 Answers
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"
5 Comments
AsYouWereAPx
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
Greggz
@AnaPeterka Let me test it out 1 second
Greggz
@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 :)
AsYouWereAPx
I figured out that when i input another name, that name replaces the name that was there before
Greggz
@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
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);