anan
anan

Reputation: 13

Is it possible in java to simplify the following if-statement?

I want to simplify this if-Statement and prevent writing "!='*'" three times. Is it possible?

if (i != '*' && j != '*' && k != '*')

Upvotes: 0

Views: 89

Answers (3)

Kaan
Kaan

Reputation: 5754

I want to simplify this if-Statement and prevent writing "!='*'" three times.

Here is a solution that simplifies the readability and intent.

First, make a simple, obvious method with a clear name (bonus: this is easy to write unit tests around):

private static boolean isValid(char i) {
    return i != '*';
}

Then in your calling code, do this:

if (isValid(i) && isValid(j) && isValid(k)) {
    // do things if all are valid
}

You can further improve the readability by making a single method which checks isValid() for an array of characters:

private static boolean allAreValid(char[] chars) {
    for (char ch : chars) {
        if (!isValid(ch)) {
            return false;
        }
    }
    return true;
}

Then your calling code becomes really clear, not just the steps but also the intent – proceed with the body of the if statement only if the characters are all valid.

char[] chars = {i, j, k};
if (allAreValid(chars)) {
    // do things if all are valid
}

Upvotes: 1

Utkarsh Sahu
Utkarsh Sahu

Reputation: 419

Yes it is possible to omit writing !='*' three times but the method will be still longer one. I would suggest to use the method which you have written in your question but if you really want to try something other out (maybe out of curiosity), you can do this:

char ch[] = {i,j,k};    /*I hope the variables i,j,k in question are char type*/
boolean flag = false;
for(int t = 0; t < ch.length; t++){
    if(ch[t] != '*')
        flag = true;
    else{
        flag = false;
        break;
    }
}
if(flag){
    //Tasks to do...
}

Writing this much is a tedious job. Thus, if (i != '*' && j != '*' && k != '*') is the most optimised one. So I would recommend using it.

Upvotes: 0

chasing fish
chasing fish

Reputation: 114

  1. use arrays:put all elements into the array, traverse the array and judge。
List<String> list = new LinkedList<>(Arrays.asList(i,j,k));
if(list.stream().noneMatch("*"::equals)){

}else{

}
  1. use string: splice elements into a string
String temp = i+j+k;
if(temp.contains("*")){
}

Upvotes: 1

Related Questions