Ternary Operators(Java)

2019-09-10 05:46发布

I was recently introduced to ternary operators. I managed to make it through a year and a half of CS school without a professor ever mentioning ternary operators. This is my first quarter where my professor is using them regularly. They seem great for shortening code. So, this is a question that will help me understand the bounds of ternary operators and when/how they can be used. Is there a way to shorten the following code block using one long statements using a ternary operator?

if(age < 18){
    minors+=1;
} else if(age < 65){
    adults+=1;
}else{
    seniors+=1;
}

3条回答
男人必须洒脱
2楼-- · 2019-09-10 06:18

You are updating three unique variables, one way to use ternaries here is something like

minors += (age < 18) ? 1 : 0;
adults += (age >= 18 && age < 65) ? 1 : 0;
seniors += (age >= 65) ? 1 : 0;
查看更多
对你真心纯属浪费
3楼-- · 2019-09-10 06:23

You can write it as a single statement:

int dummy = (age < 18) ? (minors += 1)
          : (age < 65) ? (adults += 1)
          :              (seniors += 1);

The value of dummy is unused here. It's just a way to turn the expression into a statement.

Note that I wouldn't consider writing the logic like this in practice. There are multiple side-effects in the code, and that makes it hard to understand.

I think the intent of your current code is very clear as written. Ternary expressions have a tendency to make the code harder to read, in my experience.

查看更多
何必那么认真
4楼-- · 2019-09-10 06:25

The ternary operator is not a good fit for your code because you are changing 3 different variables. I would leave your code as it is.

Suppose, on the other hand, that you had this

if (age < 18) {
    number += 1;
} else if (age < 65) {
    number = 8;
} else if (age < 90) {
    number += 2;
} else {
    number = 13;
}

This could be rewritten to look like a kind of switch:

number = age < 18 ? number + 1 :
         age < 65 ? 8          :
         age < 90 ? number + 2 :
                    13;

I think this is an improvement on the if version. However, it is not common to nest ternary operators in this way, so you may confuse people looking at your code if you used this version.

查看更多
登录 后发表回答