Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if arraylist contains a string

Tags:

java

I have this code, to find the number of female artists, male artists, or bands -

 import java.util.*;


 public class FindGender {


    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList < String > artists = new ArrayList < > ();
        int mnum = 0, fnum = 0, bnum = 0;
        artists.add("Beyonce (f)");
        artists.add("Drake (m)");
        artists.add("Madonna (f)");
        artists.add("Michael Jackson (m)");
        artists.add("Porcupine Tree (b)");
        artists.add("Opeth (b)");
        artists.add("FallOut Boy (b)");
        artists.add("Rick Ross {m}");
        artists.add("Chris Brown (m)");
        if (artists.contains("(b)")) bnum++;
        if (artists.contains("(m)")) mnum++;
        if (artists.contains("(f)")) fnum++;
        System.out.println("The number of male artists is: " + mnum);
        System.out.println("The number of female artists is: " + fnum);
        System.out.println("The number of bands is: " + bnum);
    }

 }

But the output shows - run:

The number of male artists is: 0
The number of female artists is: 0
The number of bands is: 0
BUILD SUCCESSFUL (total time: 0 seconds)

Any help would be appreciated

like image 761
Abhimanyu Chatterjee Avatar asked Dec 18 '22 21:12

Abhimanyu Chatterjee


1 Answers

Contains and containing a part of a String are different. In order to return true, it should match to the whole String.

This works

for (String item : artists) {
        if (item.contains("(b)")) bnum++;
        if (item.contains("(m)")) mnum++;
        if (item.contains("(f)")) fnum++;    
}
like image 87
Suresh Atta Avatar answered Jan 08 '23 01:01

Suresh Atta