NumberFormatException error (parseInt)

前端 未结 2 1290
南笙
南笙 2021-01-13 06:52

Hopefully a very simple query, but it\'s left me scratching my head.

I have a string, which is just a single integer, and I\'m trying to then get that integer out as

相关标签:
2条回答
  • 2021-01-13 07:31

    If the string is really 1, the exception can't happen. So I would say the string is not actually 1.

    do a data.toCharArray() and print each character's code (cast to int). It may turn out that there is a hidden character before the digit, for example. (edit: it appears iluxa mentioned this option in a comment while I was writing the answer)

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

    0 讨论(0)
  • 2021-01-13 07:42

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

    The data you received is only a part of it:

    The data received or the data to be sent starts from the offset in the buffer, and runs for length long.

    So to convert the data to a String you should use this constructor:

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

    Note that I specify the UTF-8 encoding here, as not specifying an encoding would result in the platform default encoding to be used, which is generally not what you want.

    0 讨论(0)
提交回复
热议问题