在转换字符为整数时,apache的commons包中有一个NumberUtils类,方便的提供了这种功能。共有2种函数一个带自定义默认值,一个取缺省默认值(0)。函数原型如下:
public static int stringToInt(String param, int defaultValue);
public static int stringToInt(String param);
测试程序如下:
import org.apache.log4j.Logger;
import org.apache.commons.lang.NumberUtils;
public class Test
{
private static Logger log = Logger.getLogger(Test.class);
public void testNumberUtil()
{
String strNull = null;
String strBlank = "";
String strChar = "a";
String strFloat = "7.2";
String strInt = "7";
log.debug("--- testing NumberUtils.stringToInt(String param, int defaultValue)...");
log.debug(" NumberUtil.stringToInt(null,-1):" + NumberUtils.stringToInt(strNull,-1));
log.debug(" NumberUtil.stringToInt(/"/",-1):" + NumberUtils.stringToInt(strBlank,-1));
log.debug(" NumberUtil.stringToInt(/"a/",-1):" + NumberUtils.stringToInt(strChar,-1));
log.debug(" NumberUtil.stringToInt(/"7.2/",-1):" + NumberUtils.stringToInt(strFloat,-1));
log.debug(" NumberUtil.stringToInt(/"7/",-1):" + NumberUtils.stringToInt(strInt,-1));
log.debug("--- testing NumberUtils.stringToInt(String param)...");
log.debug(" NumberUtil.stringToInt(null):" + NumberUtils.stringToInt(strNull));
log.debug(" NumberUtil.stringToInt(/"/"):" + NumberUtils.stringToInt(strBlank));
log.debug(" NumberUtil.stringToInt(/"a/"):" + NumberUtils.stringToInt(strChar));
log.debug(" NumberUtil.stringToInt(/"7.2/"):" + NumberUtils.stringToInt(strFloat));
log.debug(" NumberUtil.stringToInt(/"7/"):" + NumberUtils.stringToInt(strInt));
}
public static void main(String[] args)
{
Test testCase = new Test();
testCase.testNumberUtil();
}
}
测试结果如下:
--- testing NumberUtils.stringToInt(String param, int defaultValue)...
NumberUtil.stringToInt(null,-1):-1
NumberUtil.stringToInt("",-1):-1
NumberUtil.stringToInt("a",-1):-1
NumberUtil.stringToInt("7.2",-1):-1
NumberUtil.stringToInt("7",-1):7
--- testing NumberUtils.stringToInt(String param)...
NumberUtil.stringToInt(null):0
NumberUtil.stringToInt(""):0
NumberUtil.stringToInt("a"):0
NumberUtil.stringToInt("7.2"):0
NumberUtil.stringToInt("7"):7