您的位置:首页 > 其它

三元函数的复习

2016-09-07 22:21 183 查看

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( "" );
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  函数