Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is there a cleaner approach to an if statement with a slew of ||'s

Tags:

java

I know this question is basic but I am looking for a less-clumsy approach to the following if statement:

if ((sOne.Contains('*')) || (sOne.Contains('/')) || (sOne.Contains('-')) || (sOne.Contains('+')) || (sOne.Contains('%'))){ 

I should also note that sOne.Contains() refers to the following code...

public boolean Contains(char key) {
    // Checks stack for key
    boolean retval = arrs.contains(key);
    return retval;

}

It should also be noted that those five chars will never be changed.

like image 211
Ken Hall Avatar asked Mar 19 '17 01:03

Ken Hall


4 Answers

You could use a breaking for-each loop over a character array:

for (char c : "*/-+%".toCharArray()) {
    if (sOne.Contains(c)) {
        // ...
        break;
    }
}

If you're extremely concerned about performance you might also want to pull out the toCharArray() call and cache the result in a static final char[] constant.

You could even use this strategy to define other convenience methods on your sOne object, like ContainsAny or ContainsAll (credit to Sina Madrid for the name ContainsAny):

public boolean ContainsAny (CharSequence keys) {
    for (int i = 0; i < keys.length; i++)
        if (Contains(keys.charAt(i)) return true;

    return false;
}

public boolean ContainsAll (CharSequence keys) {
    for (int i = 0; i < keys.length; i++)
        if (!Contains(keys.charAt(i)) return false;

    return true;
}

Usage would look something like this:

if (sOne.ContainsAny("*/-+%")) {
    // ...
}
like image 164
gyre Avatar answered Oct 08 '22 19:10

gyre


You can try using regular expression like this

if (sOne.matches(".*[-*/+%].*")) {
  // your code
}
like image 28
Meme Composer Avatar answered Oct 08 '22 19:10

Meme Composer


Somewhere, you need the characters in a list:

List<Character> keys = Arrays.asList('*', '/', '-', '+', '%');

And then you can do:

if (keys.stream().anyMatch(sOne::Contains)) {
like image 32
xehpuk Avatar answered Oct 08 '22 19:10

xehpuk


How about this method: Items are your keys stored in an Array.

public static boolean stringContainsItemFromList(String inputStr, String[] items)
{
    for(int i =0; i < items.length; i++)
    {
        if(inputStr.contains(items[i]))
        {
            return true;
        }
    }
    return false;
}
like image 33
Hendrik Avatar answered Oct 08 '22 19:10

Hendrik