Integer.parseInt does not parse String to int

10,535

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");
Share:
10,535
Sushan Ghimire
Author by

Sushan Ghimire

In the end, only three things matter: how much you loved, how gently you lived and how gracefully you let go of things not meant for you. --Buddha

Updated on June 26, 2022

Comments

  • Sushan Ghimire
    Sushan Ghimire almost 2 years

    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?

  • Uncle Iroh
    Uncle Iroh about 11 years
    he did say there was no exception, but trimming is a good suggestion all the same.
  • Kyle
    Kyle about 11 years
    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.