Here is the contents of my ArrayList contain
HPDH-1,001, Check-out date: 7/7/7
JTI-1,001, Check-out date: 7/7/7
My code:
for (int i = 0; i < contain.size(); i++) {
if (contain.get(i).contains(code)) {
System.out.println(contain.get(i));
}
}
The thing is my variable code was String "JTI-1" Why isn't it giving me the JTI-1 output? I am trying to get it to display the value of the variable code. I want to remove the contain.get(i) if it would just give me the one I typed in.
The enhanced for loop (sometimes called a "for each" loop) can be used with any class that implements the Iterable interface, such as ArrayList .
Iterating over a list can also be achieved using a while loop. The block of code inside the loop executes until the condition is true. A loop variable can be used as an index to access each element.
I think fundamentally the code is correct. I would check your inputs and make sure they're really what you think.
I would perhaps rewrite your loop as:
for (String s : contain) {
if (s.contains(code)) {
// found it
}
}
to make use of the object iterators (the above assumes you have an ArrayList<String>
). And perhaps rename contain
. It's not very clear what this is.
The code is correct assuming List of strings. I have not modified any of your source code just to give you idea that it works fine.
List<String> contain = new ArrayList<String>();
contain.add("HPDH-1,001, Check-out date: 7/7/7");
contain.add("JTI-1,001, Check-out date: 7/7/7");
String code = "JTI-1 ";
for (int i = 0; i < contain.size(); i++) {
if (contain.get(i).contains(code.trim())) {<---Use trim it is possible that code may have extra space
System.out.println(contain.get(i));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With