Java ParseInt Sanity Check
Asked Answered
F

2

6

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
Ferro answered 16/1, 2012 at 13:19 Comment(7)
I notice that you have a trailing "." on the first line. Perhaps a copy-past error?Immobility
Ahh yes, ignore that. Copy and paste error indeed. Thanks :)Ferro
"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." 1) Enclose single quotes around the value in the println statement. 2) System.out.println("How long is this piece of String? " + length.length());Emalee
Thanks for that Andrew. Length is: 23 Length of length is: 3 So where the heck is the extra character...Its not appearing in the output?Ferro
What do you get for length.getBytes()? I expect (byte[]) [50, 51]Hydrodynamic
System.out.println(length.getBytes()); [B@a6aeedFerro
System.out.println(Arrays.asList(length.getBytes())); of courseDangle
E
7

Try this variant:

int test= Integer.parseInt(length.trim());
Emalee answered 16/1, 2012 at 13:38 Comment(2)
That sorted it, thanks very much! I'm assuming the byte 13 was counted as whitespace by the trim?Ferro
Not sure. But trim() will get rid of most things in a String that are not visible.Emalee
F
3

There might be unseen characters in this string.

My idea: use a regex with a Pattern/Matcher to remove all the non-numerals in your string, then parse it.

Fouquet answered 16/1, 2012 at 13:29 Comment(4)
Normally I would. But this problem has got me very interested in finding out why the extra character, whatever it may be, isn't appearing within the System.Out.Ferro
It could be one of those non-printable control characters that you can only find by issuing System.out.println(Arrays.toString(length.getBytes()));Ordonnance
[50, 51, 13] - I think 13 is a carriage return?Ferro
13 is indeed the carriage return / line feed or \n character.Ordonnance

© 2022 - 2024 — McMap. All rights reserved.