In Java, is there a more concise method for if statements with a large number of |

I know this problem is basic, but I'm looking for a less clumsy method. 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 these five characters will never change

Solution

You can use a break each loop on a character array:

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

If you are very concerned about performance, you may also need to pull out the tochararray () call and cache the results in a static final char [] constant

You can even use this policy to define other convenient methods on the sone object, such as containsany or containsall (for the name containsany, the credit is Sina Madrid):

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;
}

The usage looks like this:

if (sOne.ContainsAny("*/-+%")) {
    // ...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>