三元运算符(Java) [英] Ternary Operators(Java)

查看:117
本文介绍了三元运算符(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近被介绍给三元运算符。我设法完成了CS大学一年半的学习,而没有教授提到三元运算符。这是我的教授经常使用它们的第一季度。它们对于缩短代码似乎很棒。因此,这个问题将帮助我理解三元运算符的范围以及何时/如何使用它们。是否可以通过使用三元运算符使用一个长语句来缩短以下代码块?

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


推荐答案

您正在更新三个唯一变量,一种在这里使用三元组的方式类似于

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;

这篇关于三元运算符(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆