Search code examples
javanumberformatexception

parseInt in Java results to NumberFormatException


I am trying to load info from a properties file and i have the following code:

int minute = Integer.parseInt(prop.getProperty("delay"));
int hour = Integer.parseInt(prop.getProperty("period"));

and while the first line works just fine, the second one where i am trying to load a int variable throws a NumberFormatException. The specific exception message is:

java.lang.NumberFormatException: For input string: "1 "
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)

Currently, In my properties file value of delay is 1 and period is 5.

And when I run this program and prints value of minute and hour it is working fine, but in my Tomcat log console exception above occurs. Please help me to solve this problem? thanks in advance!


Solution

  • There appears to be trailing white space in your property (since you get "1 " in the Exception). You could call String.trim() which Returns a copy of the string, with leading and trailing whitespace omitted. Something like

    int minute = Integer.parseInt(prop.getProperty("delay").trim());
    int hour = Integer.parseInt(prop.getProperty("period").trim());