Why does this work, but not as I expected? Java conditional operator

Walter :

I'm learning Java and was doing this little time display. Then this part got tricky:

int second = 66;
second = ((second >= 0) && (second < 60) ? second : (second % 60) & (minute += second / 60));

Return second if between 0 and 60, else return second%60 and increase the minute. I expected it to work, but the output of second is: 1

Without the

(minute += second / 60)

and it worked. Change 60 to anything esle and watch the value of second changes as well. What's wrong with it?

Jon Skeet :

Your & is performing a bitwise & of the new minute value with second % 60, which seems very unlikely to be a good idea.

Given that you want a side-effect, I'd strongly recommend not using a conditional operator here - just use an if statement:

if (second > 60)
{
    minute += second / 60;
    second = second % 60;
}

(If you need to handle negative values, you'll probably need more code - it depends on what result you want.)

The lesson to take away here is that the conditional operator is used to compute a value. In your case, you're really interested in taking actions rather than computing a value: "if the second variable isn't already normalized, make changes to both second and minute". That should make you think of an if statement rather than the conditional operator. There are plenty of times that you can use a conditional operator, but it would be clearer to use an if statement.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31353&siteId=1