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?
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
The third method you can use to check if one String contains another in Java is contains() method of String. This method returns true if a substring is present in String, or false otherwise. The only difference between contains() and indexOf() is that the former returns a boolean value while later returns an int value.
In Java, a string is an object that represents a number of character values. Each letter in the string is a separate character value that makes up the Java string object. Characters in Java are represented by the char class. Users can write an array of char values that will mean the same thing as a string.
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.
Convert the Array
to a List
and then use the contains
method to check.
Arrays.asList(cancelWords).contains(value)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With