我现在写一个资料的上传,更新,有一个是价格的字段,我在接口中设置了价格,但是为非必须,但是,下面的一个用Integer.parseInt(price)会在price为空时报错。我该如何解决这个问题呢?
前端 用的是 text的,在接口中,统一用的是String 接收的。其它字段为空时,都不报错,在这个要转换时,为空时,才会报错。
推荐你的 priceIn 改为 Integer类型
Integer priceIn = null;
if(StringUtils.isNotBlank(price)){
priceIn = Integer.parseInt(price)
}
最好还是接受的时候直接用 Integer 前端改下。不然就做个异常处理
int priceIn = StringUtils.isEmpty(price) ? 0 : Integer.parseInt(price)
price!=null&&!"".equals(price)
@RequestParam注解中有个默认值defaultValue, 设置为你想要的值即可。例如 接收的价格没有传值 默认为0 就将defaultValue="0"
null !=price && !"".equals(price)
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
//引入commons-lang3之后直接通过工具类判空再做处理
Integer priceIn = null;
if(StringUtils.isNotBlank(price)){
priceIn = Integer.parseInt(price)
}
前端设置type="number"应该没有什么问题
解决办法:我看上边有人也已经说的差不多了,加入非空判断。是可以
遇到这种问题其实最好加个try catch捕获一下,然后再加入你的逻辑
try {
yourprice= Integer.parseInt(price.trim());
} catch (NumberFormatException e) {
System.out.println(e);
}
补充:如果你是安卓的应用代码:
if (!TextUtils.isEmpty(price)) {
}
cn.hutool.core.util
StrUtil.isNotBlank(price)
其实可以try捕捉错误,然后在catch处理错误 你可以返回错误信息 但是考虑到是非必要参数那么建议在catch里面设置默认值
if判断非空