Matt Smith
Matt Smith

Reputation: 975

Checking if String x equals any of the Strings from String[]

I am trying to set a boolean true if a user-entered string equals any of the strings from a string array.

I have improvised and came up with this

String[] cancelWords = {"cancel", "nevermind", "scratch that"};
boolean valueEqualsCancel = true;
for(String cancelWord : cancelWords) {
  if(!valueEqualsCancel) break;
  valueEqualsCancel =  valueEqualsCancel && value.equals(cancelWord);
}

But valueEqualsCancel is never true.

Any tips?

Upvotes: 8

Views: 28233

Answers (12)

palacsint
palacsint

Reputation: 28865

If you have Apache Commons Lang you can use StringUtils.equalsAny():

String[] cancelWords = {"cancel", "nevermind", "scratch that"};
boolean valueEqualsCancel = StringUtils.equalsAny(value, cancelWords);

Upvotes: 4

Matt
Matt

Reputation: 948

Here is a 2-liner using Java 8 that is easy to read:

String[] cancelWords = {"cancel", "nevermind", "scratch that"};
boolean valueEqualsCancel = Arrays.stream(cancelWords).anyMatch(value::equals);

Upvotes: 6

John Snow
John Snow

Reputation: 1007

I guess this should help:-

import java.util.Scanner;


public class check4 {
    public static void main(String args[])
    {
       Scanner scan = new Scanner(System.in);
       String value = scan.nextLine().toString();
       String[] cancelWords = {"cancel", "nevermind", "scratch that"};
       boolean valueEqualsCancel = false;
       for(int i=0;i<cancelWords.length;i++) {
          if(value.equals(cancelWords[i])) {
             valueEqualsCancel = true;
             break;
          }
       }
       System.out.println(valueEqualsCancel);
    }
}

Input:

camel

Output:

true

Upvotes: 0

jboi
jboi

Reputation: 11892

The solution that fits best to your situation depends a bit on the number of cancel words and the necessity to compare case insensitive or not. I'Ve added code for two possbile ways to implement:

// I would use a HashSet which needs constant time to compare, even with long lists of cancel words
// Note, that the use of toLowerCase() makes the comparison case insensitive.
@Test
public final void test2() {
    String value = "nevermind";
    HashSet<String> cancelWords = new HashSet<String>();
    cancelWords.addAll(Arrays.asList(new String[] {"cancel", "nevermind", "scratch that"}));

    boolean valueEqualsCancel = cancelWords.contains(value.toLowerCase());
    System.out.println("test2: " + valueEqualsCancel);
}

// You might like to know, which cancel word it was
@Test
public final void test3() {
    String value = "nevermind";
    String[] cancelWords = {"cancel", "nevermind", "scratch that"};
    Arrays.sort(cancelWords); // Prepare for binary search

    // The returned value indicates either which cancel word was used or, that nothing was found with result < 0.
    System.out.println("test3: nevermind " + Arrays.binarySearch(cancelWords, "nevermind"));
    System.out.println("test3: cancel " + Arrays.binarySearch(cancelWords, "cancel"));
    System.out.println("test3: something totally different " + Arrays.binarySearch(cancelWords, "something totally different"));
}

Upvotes: 0

Obzer_G
Obzer_G

Reputation: 1

Use this Method

public static boolean  isContainsWords(String[] words,String Targent){

               boolean flag;
               for(String buf : words){
                     if(buf.equals(Targent))
                          return flag = true;
               }
               return flag = false;

}

It seems perfect

Upvotes: 0

JHS
JHS

Reputation: 7871

Convert the Array to a List and then use the contains method to check.

Arrays.asList(cancelWords).contains(value)

Upvotes: 6

Anuswadh
Anuswadh

Reputation: 552

try

 String[] cancelWords = {"cancel", "nevermind", "scratch that"};     
  boolean valueEqualsCancel = true;     
  for(String cancelWord : cancelWords) {      
  if(!valueEqualsCancel) break;     
   valueEqualsCancel =  !(valueEqualsCancel && value.equals(cancelWord));     
 }

Upvotes: 0

Fedy2
Fedy2

Reputation: 3207

valueEqualsCancel is never true because you don't exit from the loop when you find the cancelWord.

In order to reach the break statement you need valueEqualsCancel to be false.

If you for example search for "cancel" after the first loop the variable valueEqualsCancel is:

valueEqualsCancel =  valueEqualsCancel && value.equals(cancelWord) = TRUE && TRUE = TRUE;

so on the second loop you don't break. Then you evaluate the expression again

valueEqualsCancel =  valueEqualsCancel && value.equals(cancelWord) = TRUE && FALSE = FALSE;      

therefore on third loop you will exit and valueEqualsCancel is false.

You can correct your code in this way:

String[] cancelWords = {"cancel", "nevermind", "scratch that"};
boolean found = false;
for(String cancelWord : cancelWords) {
  found = value.equals(cancelWord);
  if (found) break;
}

Upvotes: 4

Luke Taylor
Luke Taylor

Reputation: 9599

Use this method:

public boolean containsWord(String word, String[] words) {
   for(String cancelWord : words) {
      if(word.equals(cancelWord)) {
        return true;
      }
   }
   return false;

}

I hope this helps.

Upvotes: 0

arshajii
arshajii

Reputation: 129517

You can do something like:

Arrays.asList(cancelWords).contains(value)

(see Arrays.asList())

If you're going to be doing multiple queries like this, then put all of your words in a Set and query that.

Upvotes: 25

Richard Sitze
Richard Sitze

Reputation: 8463

Your initial value is off, and the flow can be improved:

String[] cancelWords = {"cancel", "nevermind", "scratch that"};
boolean valueEqualsCancel = false; // fix
for(String cancelWord : cancelWords) {
  if(value.equals(cancelWord)) {
    valueEqualsCancel =  true;
    break;
  }
}

Upvotes: 0

Curt
Curt

Reputation: 5722

 foreach(string thisWord in cancelWords)
    if thisWord.equals(value)
       return true;

 return false;    // Fall-through

Upvotes: 0

Related Questions