Home » Java » java – How to calculate the result list numbers in column?-Exceptionshub

java – How to calculate the result list numbers in column?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m using SpreadsheetMapper tool, I want to calculate the result listed numbers in a column.

This code is not working when I use the result list.

<#function TW nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum >
  </#if>
</#function>
${TW(result['TotalWeightListResult']!)}

https://prnt.sc/r3h137

It works when I use static listed numbers.

<#function TW nums...>
  <#local sum = 0>
  <#list nums as num>
    <#local sum += num>
  </#list>
  <#if nums?size != 0>
    <#return sum >
  </#if>
</#function>
${TW(10 20)}

reference – https://freemarker.apache.org/docs/ref_directive_function.html

here is the first thing I’m thinking – How to calculate the listed numbers from the child datastore?

How to&Answers:

If you declare TW with nums... parameter, and you pass a list to TW, it will be just the first element inside nums. That’s because parameters have no declared type in FreeMarker, so it’s not obvious what you meant.

There’s a further confusing coincidence in you example. If you are sending somethingMissing! to TW, then the first element of nums will be an empty string, which is the result of the expression! operation. Because + is overloaded to work both as addition, and as string concatenation, sum += num will no fail, instead, it will do a string concatenation. So first it converts sum to the string "0", and then append the empty string to it. So you end up with return value "0", a string, which when it’s printed, looks just like the number 0. But it’s not really a 0 number.

So, just use <#function TW nums>, then it will work as expected. In case you want to pass a literal list, you can write TW([10, 20]) then. But I guess typically you don’t want to pass a predefined list to TW, and so the extra [] is not a big deal.