7

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?

Rangi Lin
  • 9,303
  • 6
  • 45
  • 71
Matt Smith
  • 965
  • 3
  • 13
  • 24
  • Your loop does not quit when you find "cancel". It will be set to false since "nevermind" and "scratch that" do not equal "cancel". – RaptorDotCpp Aug 04 '13 at 15:29
  • 1
    Once you find a match, exit the loop. Don't cycle over the remaining elements. – Tony Ennis Aug 04 '13 at 15:36
  • check this for jdk8 [link](https://stackoverflow.com/questions/8992100/test-if-a-string-contains-any-of-the-strings-from-an-array?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – wizardInCloud May 19 '18 at 10:06

12 Answers12

23

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • 1
    +1 for putting the words into a set. I disagree with the `asList` approach, though, because that adds quite a bit of overhead. It's fine for small arrays, but it would have a noticeable effect on large data sets. – Kevin Aug 04 '13 at 18:54
  • 1
    @Kevin Thanks for the upvote :) Why do you say `asList` adds overhead? It creates a list backed directly by whatever array you pass in (no copying involved), so there is very little associated cost, regardless of the array size. – arshajii Aug 05 '13 at 01:08
  • I stand corrected. I assumed that creating the list was O(n). – Kevin Aug 05 '13 at 03:14
5

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

Arrays.asList(cancelWords).contains(value)

JHS
  • 7,761
  • 2
  • 29
  • 53
  • contains will not do because value has to be exactly as a string from the array. e.g. value might be "cancel that" but that wouldn't equal "cancel" from the array. – Matt Smith Aug 04 '13 at 15:23
  • With the `equals` method in the question. I think the OP is trying to do the same. – JHS Aug 04 '13 at 15:26
  • This is a good answer in that it encourages the OP to use constructs that already exist instead of coding something by hand. I can't comment on whether or not the exact solution presented is what the OP needs. – Tony Ennis Aug 04 '13 at 15:34
  • @MattSmith [`Collection.contains()`](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#contains(java.lang.Object%29) – NullUserException Aug 04 '13 at 15:35
5

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);
Matt
  • 828
  • 8
  • 25
4

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;
}
Fedy2
  • 3,147
  • 4
  • 26
  • 44
  • The OP says nothing about the list being sorted, not the number of times the search would be performed. Thus I don't know if the binarySearch comment is appropriate. – Tony Ennis Aug 04 '13 at 15:32
  • This looks like the best answer to me. Writing a for loop to search an array and break when a result is found is a pattern that I use frequently in Java. – Kevin Aug 04 '13 at 18:55
2

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

String[] cancelWords = {"cancel", "nevermind", "scratch that"};
boolean valueEqualsCancel = StringUtils.equalsAny(value, cancelWords);
palacsint
  • 28,416
  • 10
  • 82
  • 109
0
 foreach(string thisWord in cancelWords)
    if thisWord.equals(value)
       return true;

 return false;    // Fall-through
Curt
  • 5,518
  • 1
  • 21
  • 35
0

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;
  }
}
Richard Sitze
  • 8,262
  • 3
  • 36
  • 48
0

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.

Luke Taylor
  • 9,481
  • 13
  • 41
  • 73
0

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
Curt
  • 5,518
  • 1
  • 21
  • 35
John Snow
  • 977
  • 7
  • 12
0

try

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

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

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

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"));
}
jboi
  • 11,324
  • 4
  • 36
  • 43