1

I am trying to check if a string is valid by checking if it contains special words that are set in an array

String email = "this@webmaster";
    tv.setText(Boolean.toString(checkEmailValidity(email)));

}

public boolean checkEmailValidity(String email) {

    String[] specialWords = {"webmaster", "government"};
    if( email.contains(specialWords.toString())||email.contains(" ")){
        return false;
    }
    return true;
}

The result is always true so the statement that checks the email with the specialWords is not good. What can I do?

Dani
  • 1,825
  • 2
  • 15
  • 29
ladyBug
  • 69
  • 1
  • 9
  • "this@webmaster" has "webmaster" in itself, so it returns true, what did you expect? – Mehran Zamani May 20 '17 at 09:29
  • I wanted it to return false if the email contained one of the special words. I found the logical error thank you as I needed to insert ! in front of email.contains(specialWords.toString()). Thank you for the explanation – ladyBug May 20 '17 at 09:40
  • from [this](http://stackoverflow.com/questions/8992100/test-if-a-string-contains-any-of-the-strings-from-an-array) : `public static boolean stringContainsItemFromList(String inputStr, String[] items) { return Arrays.stream(items).parallel().anyMatch(inputStr::contains); }` – Mehran Zamani May 20 '17 at 09:46

4 Answers4

2

If you are using java 8 you can do this way

return Arrays.stream(specialwords).parallel().anyMatch(email::contains);
Denis Ismailovski
  • 311
  • 1
  • 7
  • 15
1
Pattern regex = Pattern.compile("\\b(?:webmaster|government)\\b");
Matcher regexMatcher = regex.matcher(email);
boolean contains = regexMatcher.find();
Cătălin Florescu
  • 5,012
  • 1
  • 25
  • 36
0

Try This:

public static boolean checkEmailValidity(String email) {
        String[] specialWords = {"webmaster", "government"};
        Set<String> set = new HashSet<String>(Arrays.asList(specialWords));
    return set.contains(email);
    }

This is for your code:

public static boolean checkEmailValidity(String email) {
        String[] specialWords = {"webmaster", "government"};
        boolean flag = false;
        if (!email.contains(" ")) {
            for (int index = 0; index < specialWords.length; index++) {
                if (email.contains(specialWords[index].toString())) {
                    flag = false;
                    break;
                } else {
                    flag = true;
                }
            }
        }
        return flag;
    }
Jay Prakash
  • 787
  • 6
  • 22
-1
String email = "this@webmaster";
    tv.setText(Boolean.toString(checkEmailValidity(email)));


public boolean checkEmailValidity(String email) {

    String[] specialWords = {"webmaster", "government"};
    if( email.contains(specialWords.get(0))||email.contains(specialWords.get(1))){
        return false;
    }
    return true;
}
Mehran Zamani
  • 831
  • 9
  • 31