3

The code below is from a Servlet trying to read data from a submitted html form. The variable fieldValue is a String and prints correct value (like so BizStr: 5) but when I try to parse this value to integer, it does not print anything.

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");
    }
  }
}

Why is this string not being parsed into integer?

10
  • Do you have a stack trace from an error? Commented May 1, 2013 at 23:10
  • 5
    I'd suspect there's an extra space there or something, Integer.parseInt throws a NumberFormatException, which gets eaten somewhere Commented May 1, 2013 at 23:10
  • 1
    Can you please do out.println("BizInt: "+ Arrays.toString(fieldValue.toCharArray())+"\n"); and edit what that does into your answer Commented May 1, 2013 at 23:10
  • 1
    @iluxa made a good guess, it may be white space. The following code should strip whitespace (including non-visible characters) from your string if you want to try it. fieldValue.replaceAll("\\s","") (Note, that won't change the value of the variable, it will just return it. So you can use that code inside your parseInt call or do fieldValue = fieldValue.replaceAll("\\s","");) Commented May 1, 2013 at 23:13
  • 1
    @Kyle kinda embarrassed, yes you are right, it is due to whitespace. thank you all Commented May 1, 2013 at 23:17

1 Answer 1

10

Testing:

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

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

Try trim() on the fieldValue before parsing:

out.println("BizInt: "+ Integer.parseInt(fieldValue.trim() )+"\n");
Sign up to request clarification or add additional context in comments.

2 Comments

he did say there was no exception, but trimming is a good suggestion all the same.
Another note to add to the conversation going on in the comments, this answer is probably a better answer than my replaceAll comment depending on how the number is being used. This will trim trailing and leading whitespace, so ` 5 ` would be acceptable, but 5 5 would still thrown an exception alerting you to a problem. If you don't care and want to try and parse all the numbers even if a space is in the middle, the replaceAll is better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.