本文介绍了具有Integer.parseInt()的NumberFormatException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Integer.parseInt()有问题。
具体来说,我的代码是这样做的:

I've a problem with Integer.parseInt().Specifically my code do this:

serverPort变量是一个正确初始化为1910的整数

serverPort variable is an int correctly initialized to 1910

byte[] multicastMessage = (serverAddress+"::"+String.valueOf(serverPort)).getBytes();

byte[] receivedBytes = receivePacket.getData();
receivedString = new String(receivedBytes, "UTF-8");

String[] decodedString = receivedString.split("::");
serverPort = Integer.parseInt(decodedString[1]);

请注意,当我在控制台中打印decodedString [1]时,会正确打印1910。但是当我调用Integer时.parseInt()引发NumberFormatException。

Note that when I print decodedString[1] in console is correctly printed 1910. But when I call Integer.parseInt() a NumberFormatException is raised.

我也尝试在第一行中使用Integer.toString(serverPort)或使用新的Integer(decodedString [1])。

I've tried also using Integer.toString(serverPort) in first row or using new Integer(decodedString[1]).intValue() in last row without success.

我怀疑使用字节产生的转换问题(我无法避免),但是我对字节不太熟悉

I suspect the conversion issue born using byte (I can't avoid it), but I'm not so familiar with byte struct.

编辑:

Exception in thread "Thread-0" java.lang.NumberFormatException: For input string: "1910"
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 ClientThread.run(ClientThread.java:60)


推荐答案

我看到您的评论,trim()仍在提供NumberFormatException。

I see your comment that trim() is still providing the NumberFormatException.

我的下一个猜测是,有一个不可见的ASCII字符,例如BOM()在您字符串中的某个位置。最好的检查方法是通过以下函数运行字符串:

My next guess is that there is an invisible ASCII character such as a BOM (bye order mark) somewhere in your String. The best way to check this would be to run your string through the following function:

public static String displayCharValues(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
    sb.append((int) c).append(",");
}
return sb.toString();}

如果BOM是现在,您将看到65279作为序列的一部分被打印出来。如果您的字符串包含有效数字,则您应该只看到与数字相关联的相应ASCII代码()。您应该看到1910字符串打印为49、57、49、48。

If a BOM is present then you will see 65279 printed out as part of the sequence. If your String contains valid numbers then you should only see the corresponding ASCII codes assocatied with numbers (http://www.asciitable.com/). You should see your 1910 string print out as 49,57,49,48.

这篇关于具有Integer.parseInt()的NumberFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:55