三元函数的复习

Constructing a string that does not include integer if it is 0 in Java?怎样构造一个不包含Integer数据为0时的String?

这片文章是对三元函数的一个复习和深入理解,请同学们需要的自己看一下。

Let’s say that I have:
让我谈一谈:

int hours = 0;
int minutes = 0;
int seconds = 5;
System.out.println("Simplified time: " + hours + ":" + minutes + ":" + seconds + ":");

it will obviously print out:
这明显打印出:

Simplified time: 0:0:5:

Does anyone have any idea to make it print out like:
有人能有其他想法让它打印出像下面的:

Simplified time: 5:

without using some if else statements?
不使用if else判断语句?
Of course if (hours>0) I would like it to print out the whole Print
当然,我希望如果(时>0)的时候打印整个打印
statement Like if (hours=3) I want it to print out:
语句,例如(时>3)我想打印出:

Simplified time: 3:0:5:

That is what if-else statements are for.
这就是if - else语句。
But you could do some ternary operators too.
但是你也可以做一些三元运算控制。

System.out.println( "Simplified time: " + ( hours > 0 ? hours + ":" : "" ) + (minutes > 0 || hours > 0 ? minutes + ":" : "" ) + seconds + ":" );

Although this looks like a jumbled mess and I would suggest using
但是这看上去显得很乱所以我建议使用
if-else for improved readability.
if-else语句提高可读性。

If you want to go this approach though,
如果你想用这个方法
I would concatenate a String using Stringbuilder or the sorts
我将连结一个String运用StringBuilder或者在打印之前排好序如下
before printing such as:

Stringbuilder sb = new Stringbuilder();
sb.append( hours > 0 ? hours + ":" : "");
sb.append( minutes > 0 || hours > 0 ? minutes + ":" : "");
sb.append( seconds );

System.out.println( sb.toString );

This just enhances the readability and as such would look cleaner
这正好提高了可读性并且看上去比使用很多三元运算表达的要略显干净
than putting a lot of ternary expressions in the same line.

If you are wondering what Ternary operators are, think of it as a
如果你觉得疑惑什么是三元元算控制,
glorified if-else statement.
想象下用if-else语句表示。
for example:如下所示

sb.append( hours > 0 ? hours + ":" : "" );
is the same as:

if( hours > 0 )
    sb.append( hours + ":" );
else
    sb.append( "" );
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值