简体   繁体   中英

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.

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

#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. In case you have the NumberTool loaded into your context a better solution than parseInt is the following:

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

Sometimes the NumberTool is also loaded as $number .

However, a little drawback is, that the NumberTool simply parses the first number it finds and ignores the rest, so "123a" => 123.

You have to cast string $SplitMap.get("$pod.id") into Number or int :

#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 ). You have to check what name for NumberTool is used in your Velocity environment.

toNumber method returns:

the object as a Number or null if no conversion is possible

If you want to have explicite an int variable, not a Number object, you can use the intValue method on the result. So the second line from above code will looks like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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