NumberFormatException in Java for a string that is

2019-09-17 08:55发布

问题:

I am implementing socket programming using Java. I get this error.

My code is:

public class UDPServer  {

public static void main(String[] args) throws Exception {
    byte[] data = new byte[1024];
    byte[] sendData = new byte[1024];
    byte[] num1b = new byte[1024];      
    String num1String;
    DatagramPacket recievePacket;
    String sndmsg;
    int port;
    DatagramSocket serverSocket = new DatagramSocket(9676);
    System.out.println("UDP Server running");
    byte[] buffer = new byte[65536];
    while(true) {
        recievePacket = new DatagramPacket(num1b, num1b.length);
        serverSocket.receive(recievePacket);
        num1String = new String(recievePacket.getData());
        System.out.println(num1String);
        System.out.println(num1String.length());
         int numbers2=Integer.parseInt(num1String);

I run my UDP client:

Enter number 1 :2
Enter number 2 :5
Enter number 3 :4
Enter number 4 :3
Enter number 5 :1
Select Protocol: 
1.UDP
2.TCP
1
Data sent to server

My Server Shows this:

$ java UDPServer 
UDP Server running
waiting for data from client 
2
1024
Exception in thread "main" java.lang.NumberFormatException: For input string: "2"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at UDPServer.main(UDPServer.java:49)
$

What is causing this error? Why is my string 2 not getting converted?

回答1:

You probably have an issue with your client code. However, a simple workaround would be to take the first character of num1String:

int numbers2=Integer.parseInt(num1String.substring(0, 1));


回答2:

This should work:

num1String = new String(recievePacket.getData(), 0, receivePacket.getLength());

When you receive a packet from the server, receivePacket.getLength() will give you the number of bytes received. The remaining bytes in the array will be unchanged as they aren't part of the last received packet, and most of them will most likely be 0. If you include those in your String, it will contain a lot of irrelevant characters at the end, mostly null-characters (depending on the remaining bytes and the default charset). And some IDE's and/or platforms may not print the whole String if it contains null-characters.