I'm trying to parse a int
from a String
array element. Here is my code:
String length = messageContents[k].replace("Content-Length:", "").replace(" ", "");
System.out.println("Length is: " + length);
int test= Integer.parseInt(length);
The System.out.println
returns the following: Length is: 23
However, when I try to parse the String
into an int
, a java.lang.NumberFormatException
gets thrown;
java.lang.NumberFormatException: For input string: "23"
I'm a bit confused how 23 wont get parsed into an int
. I can only assume that there is some other character in there that is preventing it, but I can't see it for the life of me.
Any suggestions?
Thanks
Update
Despite the String length having only two characters, Java reports its length as three:
Length is: '23'
Length of length variable is: 3
length.getBytes = [B@126804e
parseInt method as a parameter. The method throws an error if the string cannot be parsed into an integer. Note, that the code within the catch block is executed only if an exception is thrown.
Java - parseInt() Method This method is used to get the primitive data type of a certain String. parseXxx() is a static method and can have one argument or two.
Following are the declarations of parseInt () method: public static int parseInt (String s) public static int parseInt (String s, int radix) public static int parseInt (CharSequence s, int beginIndex, int endIndex, int radix)
Try this variant:
int test= Integer.parseInt(length.trim());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With