-2

I just wanna check if my String[] array contains "n" or "s".

String[] coordinatesExample = {"57.8136°s", "28.3496°e"};

private void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }

So I expected: "It works!", but in fact: "RAKAMAKAFO"

What I did wrong?

KennyWood
  • 15
  • 4
  • 3
    `"57.8136°s"`contains `"s"`, `{"57.8136°s", "28.3496°e"}` doesn't – jhamon Feb 18 '20 at 15:17
  • .contains() on ArrayList will return true if entire element exist. You are checking only "s". – kann Feb 18 '20 at 15:24
  • Does this answer your question? [Check if multiple strings exist in another string](https://stackoverflow.com/questions/3389574/check-if-multiple-strings-exist-in-another-string) – Bharat Feb 18 '20 at 17:43

3 Answers3

1

Your current solution only works if you have a String Array like this:

String[] coordinatesExample = {"57.8136°s", "28.3496°e", "s"};

Try this if you want to check if any String from your Array contains "n" or "s".

private static void isContains(String[] coordinates) {
    boolean contains = Arrays.stream(coordinates)
            .anyMatch(coordinate -> coordinate.contains("s") || coordinate.contains("n"));
    if (contains) {
        System.out.println("It works!");
    } else {
        System.out.println("RAKAMAKAFO");
    }
}
falknis
  • 141
  • 7
0

When you do Arrays.asList(coordinates) you get the list containing two items: 57.8136°s and 28.3496°e. So using .contains("s") you test if any of your items is "s" which is obviously not the case.

Alexey R.
  • 8,057
  • 2
  • 11
  • 27
0

Contains only checks to see if the list contains one of the elements which s is not one.

From the JavaDoc for the List interface

boolean contains​(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that Objects.equals(o, e).

If you did the following, it would return print It works! because the first string in the list contained an s

private static void isContains(String[] coordinates) {

    boolean contains = Arrays.asList(coordinates).get(0).contains("s");
        if (contains) {
            System.out.println("It works!");
        }else {
            System.out.println("RAKAMAKAFO");
        }
    }
}
Community
  • 1
  • 1
WJS
  • 36,363
  • 4
  • 24
  • 39