Home > OS >  java Integer.parseInt() acting weird
java Integer.parseInt() acting weird

Time:04-10

So I've been working on a server-client program where the client sends the server a string, the server splits that string to perform certain calculations.

//message sample

18011d5651,0,348,1649520496736,5,0:1010,1

then the message is stored in a string called msg

when I try to run the following line on the server side:

int d = Integer.parseInt(msg.split(",")[4]); 

it returns an error as follows

Exception in thread "main" java.lang.NumberFormatException: For input string: "5"
  at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  at java.lang.Integer.parseInt(Integer.java:580)
  at java.lang.Integer.parseInt(Integer.java:615)
  at test.test1.main(test1.java:54)
C:\Users\xxxx\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 9 seconds) ```

CodePudding user response:

Perhaps the problem is that server uses different charset enconding. You can try converting the charset to UTF-8:

    int d = Integer.parseInt(StringUtils.newStringUtf8(StringUtils.getBytesUtf8(msg.split(",")[4])));

You should import StringUtils:

  import org.apache.commons.codec.binary.StringUtils;

CodePudding user response:

the problem was solved with

.replaceAll("\0", "")

I was sending the data from a client to a proxy to a server, so in the proxy, it was reading 1000 bytes, and of which are being appeded to the last element "5" then the part that the proxy adds was appended (,0:1010,1) so there was 834 nulls. using the line above I replaced all the nulls in the message in the proxy before forwarding it to the server, then added the proxy part then sent it to the server and the processing was successful.

another way to tackle it is by removing the nulls from it on the server side, but if the server buffer was 1000 bytes we'll have an issue too, cuz the proxy appended part wouldn't be delivered. I didn't realize why that was happening until I made the buffer in the server 1100 bytes.

the solution given that the buffer in server is 1100 bytes is as follows

String msg = "18011d5651,0,348,1649520496736,5,0:1010,1".replaceAll("\0", "");
int d = Integer.parseInt(msg.split(",")[4]); 
> d = 5
> d.length() = 1
  • Related