Integer.parseInt不会将String解析为int

时间:2013-05-01 23:07:09

标签: java type-conversion

以下代码来自尝试从提交的html表单中读取数据的Servlet。变量fieldValue是一个String并打印正确的值(如此BizStr: 5)但是当我尝试将此值解析为整数时,它不会打印任何内容。

for(FileItem uploadItem : uploadItems){
  if(uploadItem.isFormField()){
    String fieldName = uploadItem.getFieldName();
    String fieldValue = uploadItem.getString();
    if(fieldName.equals("business_id")){
        out.println("BizStr: "+ fieldValue +"\n");
        out.println("BizInt: "+ Integer.parseInt(fieldValue )+"\n");
    }
  }
}

为什么不将此字符串解析为整数?

1 个答案:

答案 0 :(得分:10)

测试:

Integer.parseInt(" 5");  // space before; yields NumberFormatException

Integer.parseInt("5 ");  // space after; yields NumberFormatException

在解析之前尝试trim()上的fieldValue

out.println("BizInt: "+ Integer.parseInt(fieldValue.trim() )+"\n");