Home > database >  How to simplify this condition?
How to simplify this condition?

Time:03-19

I'm learning about using if-else else-if conditions and I am wondering if there is anyway to simplify these statement below. Can I combine all of them into one statement?

if (a < 0) {
    a = 1;
}
if (b < 0) {
    b = 1;
}
if (c < 0) {
    c = 1;
}

CodePudding user response:

It seems not possible to combine all your mentioned if statements into one as a, b, c are all independent variables. However, to make your code more readable, you can take advantage of method.

e.g. Implement a method like this:

int processNegativeNumber(int num) {
    if (num < 0) {
        return 1;
    }
    return num;
}

Now, you can call it like this:

a = processNegativeNumber(a);
b = processNegativeNumber(b);
c = processNegativeNumber(c);

CodePudding user response:

You could use ternary operator to save some chars :-)

a = a < 0 ? 1 : a;
b = b < 0 ? 1 : b;
c = c < 0 ? 1 : c;
  • Related