Java for loop with ArrayList

Here are 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 is:

 for (int i = 0; i < contain.size(); i++) { if (contain.get(i).contains(code)) { System.out.println(contain.get(i)); } } 

The fact is that my variable code was the string "JTI-1". Why doesn't it give me JTI-1 output? I am trying to get it to display the value of a code variable. I want to remove include.get (i) if it just gave me the one I entered.

+4
source share
3 answers

The code is correct under the assumption. List of lines. 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)); } } 
+6
source

I think the root code is correct. I would check your details and make sure that they are really what you think.

I would rewrite your loop as:

 for (String s : contain) { if (s.contains(code)) { // found it } } 

to use object iterators (the above assumes you have an ArrayList<String> ). And maybe rename contain . It is not clear what it is.

+8
source

Your code is correct, although I would also recommend using iterators:

 import java.util.ArrayList; import java.util.Arrays; public class Main { public static void main(String[] args) throws Exception { ArrayList<String> contain = new ArrayList<String>(Arrays.asList("HPDH-1,001, Check-out date: 7/7/7", "JTI-1,001, Check-out date: 7/7/7")); String code = "JTI"; // your loop for (int i = 0; i < contain.size(); i++) { if (contain.get(i).contains(code)) { System.out.println(contain.get(i)); } } // my suggestion for (String s : contain) { if (s.contains(code)) { System.out.println(s); } } } } 

Output:

JTI-1.001, Check-out Date: 7/7/7

JTI-1.001, Check-out Date: 7/7/7

If this result is not what you want, add more information.

+2
source

Source: https://habr.com/ru/post/1440733/


All Articles