如何使用三元运算符忽略值为0的数字。

huangapple go评论77阅读模式
英文:

how to ignore number if it is 0 using ternary operator

问题

这是我在Talend软件上尝试的部分,我在此处编写我的表达式。

这是我的数据:

{
    Obj_id: "6",
    State_District: "EAST GARO HILLS",
    Date: "2020-08-27",
    cat1: "0",
    cat2: "2",
    cat3: "0",
    cat4: "4",
    cat5: "0",
    message: "",
    toi: "1900",
    vupto: "2200",
    color: "2"
}

我想将所有值大于 "0" 的 cat 列都追加起来,就像上面的示例,我想要 2|4

但是我得到了 2|4|。意思是多了一个额外的 | <br>。
我尝试过以下方法:

(row5.cat1 > 0 ? row5.cat1 + "|" : "") + 
(row5.cat2 > 0 ? row5.cat2 + "|" : "") + 
(row5.cat3 > 0 ? row5.cat3 + "|" : "") + 
(row5.cat4 > 0 ? row5.cat4 + "|" : "") + 
(row5.cat5 > 0 ? row5.cat5 + "|" : "")
英文:

This is i am trying on Talend Software. where i am writing my expression

This is my data:

{
Obj_id: &quot;6&quot;,
State_District: &quot;EAST GARO HILLS&quot;,
Date: &quot;2020-08-27&quot;,
cat1: &quot;0&quot;,
cat2: &quot;2&quot;,
cat3: &quot;0&quot;,
cat4: &quot;4&quot;,
cat5: &quot;0&quot;,
message: &quot;&quot;,
toi: &quot;1900&quot;,
vupto: &quot;2200&quot;,
color: &quot;2&quot;
}

I want to make append all cat column whose value is greater than "0". like in above example i want 2|4

But i am getting 2|4|. Means one more extra | <br>
I tried this:

(row5.cat1&gt;0 ? row5.cat1 + &quot;|&quot; : &quot;&quot;) + (row5.cat2&gt;0 ? row5.cat2 + &quot;|&quot; : &quot;&quot;) + (row5.cat3&gt;0 ? row5.cat3 + &quot;|&quot;: &quot;&quot;) + (row5.cat4&gt;0 ? row5.cat4 + &quot;|&quot;: &quot;&quot;)+ (row5.cat5&gt;0 ? row5.cat5 + &quot;|&quot;: &quot;&quot;) 

答案1

得分: 1

你问题的标题与你的问题无关。

每当你添加一个数字(数字为 &gt; 0),你实际上是在写:将数字放入字符串中,然后加上一个竖线。因此,显然,最终的结果将是这种格式:2|3|4|5| - 包含一些数量的数字,其中所有数字,包括最后一个数字,都以竖线结束。

有许多方法可以解决这个问题。一种简单的方法是去掉末尾的竖线:

if (str.endsWith(&quot;|&quot;)) str = str.substring(0, str.length() -1);

另外,你可以重写你的代码,将其转换为一系列数字,然后使用 'joining' 收集器,这会更加现代化。

英文:

The title of your question has nothing to do with your problem.

Any time you add a number (a number is &gt; 0) you literally wrote: Put the number in the string, and then a bar. Thus, obviously, the end result will be in the format 2|3|4|5| - some amount of numbers, and all of them, including the last one, ending in a |.

There are many ways to solve this. An easy way is to lop off a trailing bar:

if (str.endsWith(&quot;|&quot;)) str = str.substring(0, str.length() -1);

alternatively, rewrite your code to turn it into a stream of numbers, and then use the 'joining' collector, that'd be a bit more modern.

huangapple
  • 本文由 发表于 2020年8月27日 23:03:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63618893.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定