Integer.parseInt不会将String解析为int

Sus*_*ire 3 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");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

为什么这个字符串没有被解析为整数?

rge*_*man 10

测试:

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

Integer.parseInt("5 ");  // space after; yields NumberFormatException
Run Code Online (Sandbox Code Playgroud)

尝试trim()fieldValue之前的解析:

out.println("BizInt: "+ Integer.parseInt(fieldValue.trim() )+"\n");
Run Code Online (Sandbox Code Playgroud)

  • 另外一个注释要添加到评论中的对话中,这个答案可能比我的`replaceAll`评论更好,这取决于数字的使用方式.这将修剪尾随和前导空格,因此`5`是可以接受的,但是`5 5`仍然会抛出异常提醒您出现问题.如果您不在乎并且想要尝试解析所有数字,即使空间位于中间,`replaceAll`也会更好. (3认同)