当前位置: 首页 > 知识库问答 >
问题:

线程“main”java中出现异常。lang.NumberFormatException:对于输入字符串:“100”[重复]

鲁向明
2023-03-14

当我从一个单独的客户端程序接收到一个整数(事务ID)转换成字符串时,我的Java UDP服务器程序的一个片段出错:

客户:

// Sending transaction ID to server
sendData = String.valueOf(transID).getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, sportno);
clientSocket.send(sendPacket);

服务器:

// Receive client's transaction ID
receiveData = new byte[1024]; // 1024 byte limit when receiving
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket); // Server receives packet "100" from client
String clientMsg = new String(receivePacket.getData()); // String to hold received packet
int transID = Integer.valueOf(clientMsg); // Convert clientMsg to integer
System.out.println("Client has sent: " + transID); // Printing integer before iteration

当客户端发送数据包时,在字符串到整数的转换过程中,我得到了以下错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "100"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.valueOf(Integer.java:766)
at server.main(server.java:46)

我还使用了整数。parseInt(clientMsg)具有类似的结果。然而,只要我没有尝试将数据包转换成整数,程序就可以将数据包打印为字符串值。

此外,虽然它在终端中显示了这一点,但当我将此错误消息复制粘贴到这篇文章中时,“100”后面跟着大量的“”s,我假设这是receiveData变量中剩余的空字节。

这些空值是我的程序失败的原因吗?如果没有,该计划失败还有什么其他原因?此外,是否有一种方法可以将事务ID整数发送到服务器,而不首先将其转换为字符串以防止此错误?

共有2个答案

薛霄
2023-03-14

试试看希望这管用

String receivedMsg = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength());
刘才俊
2023-03-14
String clientMsg = new String(receivePacket.getData()); // String to hold received packet

问题就在这里。通过忽略传入数据报的实际长度,您正在添加垃圾。应该是:

String clientMsg = new String(receivePacket.getData(), receivePacket.getOffset(), receivePacket.getLength()); // String to hold received packet
 类似资料: