下面的代码来自一个试图从提交的 html 表单中读取数据的 Servlet。变量 fieldValue
是一个字符串并打印正确的值(例如 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");
}
}
}
为什么这个字符串没有被解析成整数?
最佳答案
测试:
Integer.parseInt(" 5"); // space before; yields NumberFormatException
Integer.parseInt("5 "); // space after; yields NumberFormatException
在解析之前在 fieldValue
上尝试 trim()
:
out.println("BizInt: "+ Integer.parseInt(fieldValue.trim() )+"\n");
关于java - Integer.parseInt 不会将 String 解析为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16327860/