Error NumberFormatException (parseInt)

Hopefully a very simple request, but that left me scratching my head.

I have a string that is just one integer, and I am trying to then get that integer as an int. This at first glance should not be a problem.

// this is how I create the string (it the playload from a UDP datagram packet, // thought I don't think the origins hugely important - it juts a test run so the // stringMessage is always 1 (created by a seperate client process) ... recvSoc.receive(pac); String stringMessage = new String(pac.getData()); port = pac.getPort(); System.out.println("RECEIVED: " + stringMessage + " on port: " + port); processMessage(stringMessage); ... // Then in processMessage public void processMessage(String data) { int message; message = Integer.parseInt(data); ... 

This always fails with a NumberFormatException error. I can’t let my life determine that because of this, some ideas are very appreciated. I did not code much in Java (recently), so I would just forget something critical and what not.

 Exception in thread "main" java.lang.NumberFormatException: For input string: "1" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:481) at java.lang.Integer.parseInt(Integer.java:514) at udp.UDPServer.processMessage(UDPServer.java:85) at udp.UDPServer.run(UDPServer.java:52) at udp.UDPServer.main(UDPServer.java:156) 
+4
source share
2 answers

Note that DatagramPackate.getData() returns the entire buffer !

The data you receive is only part of this:

Received data or sent data starts with offset in the buffer and lasts for length .

So, to convert the data to String , you must use this constructor :

 String message = new String(pac.getData(), pac.getOffset(), pac.getLength(), "UTF-8"); 

Please note that here I specify the UTF-8 encoding, since not specifying the encoding, this will lead to the use of the default encoding of the platform, which is usually not what you want.

+4
source

If the string is valid 1 , an exception cannot be thrown. Therefore, I would say that the string is not really 1 .

do a data.toCharArray() and print each character code (add to int ). It may seem that there is a hidden symbol in front of the number. (editing: it seems iluxa mentioned this option in a comment when I wrote the answer)

Try data = data.trim() before passing it to parseInt(..)

+5
source

Source: https://habr.com/ru/post/1343253/


All Articles