Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ParseInt Sanity Check

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
like image 892
Tony Avatar asked Jan 16 '12 13:01

Tony


People also ask

Does parseInt throw error?

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.

When parseInt () method can be used?

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.

What is the valid declaration in parseInt () method?

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)


1 Answers

Try this variant:

int test= Integer.parseInt(length.trim());
like image 113
Andrew Thompson Avatar answered Sep 17 '22 18:09

Andrew Thompson