简体   繁体   English

如何将字符串转换为整数以在 Velocity 的循环中使用?

[英]How to convert a String to Integer for use in a loop in Velocity?

The $pod.id and $SplitMap.get("$pod.id") are not null. $pod.id$SplitMap.get("$pod.id")不为空。

This loop also works:这个循环也有效:

#set($start = 0)
#set($end = 1)

But this is not working:但这不起作用:

#set($start = 0)
#set($end = $Integer.parseInt($SplitMap.get("$pod.id")))

It gives Exception:它给出了异常:

#set($start = 0)
#set($end = $Integer.parseInt("$SplitMap.get("$pod.id"))")

This is working internally for val template takes something which is commented这是在内部工作的 val 模板需要一些注释

#set($val =1)
//Integer val = new Integer();
#set($start = 0)
#set($end = $val.parseInt($SplitMap.get("$pod.id")))

The problem with parseInt is that it throws an exception in case the string is not parseable. parseInt的问题在于它会在字符串不可解析的情况下抛出异常。 In case you have the NumberTool loaded into your context a better solution than parseInt is the following:如果您将NumberTool加载到您的上下文中,那么比parseInt更好的解决方案如下:

#set($val = 1)
#set($start = 0)
#set($end = $numberTool.toNumber($SplitMap.get("$pod.id")).intValue())

Sometimes the NumberTool is also loaded as $number .有时 NumberTool 也被加载为$number

However, a little drawback is, that the NumberTool simply parses the first number it finds and ignores the rest, so "123a" => 123.然而,一个小缺点是 NumberTool 只是解析它找到的第一个数字并忽略其余的数字,所以“123a”=> 123。

You have to cast string $SplitMap.get("$pod.id") into Number or int :您必须将字符串$SplitMap.get("$pod.id")转换为Numberint

#set( $start = 0 )
#set( $spodId = $number.toNumber($SplitMap.get("$pod.id")) )
#set( $end = $spodId )

$number is the default key name for the NumberTool , but it can be override by specifying a different name in the configuration (for example $numberTool ). $numberNumberTool的默认键名,但可以通过在配置中指定不同的名称来覆盖它(例如$numberTool )。 You have to check what name for NumberTool is used in your Velocity environment.您必须检查您的 Velocity 环境中使用的NumberTool名称。

toNumber method returns: toNumber 方法返回:

the object as a Number or null if no conversion is possible如果无法进行转换,则对象为Number或 null

If you want to have explicite an int variable, not a Number object, you can use the intValue method on the result.如果你想显式一个int变量,而不是一个Number对象,你可以对结果使用intValue方法 So the second line from above code will looks like this:所以上面代码的第二行看起来像这样:

#set( $spodId = $number.toNumber($SplitMap.get("$pod.id")).intValue() )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM