Friday, 15 April 2011

udp - NumberFormatException in Java for a string that is a number -



udp - NumberFormatException in Java for a string that is a number -

i implementing socket programming using java. error.

my code is:

public class udpserver { public static void main(string[] args) throws exception { byte[] info = 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 udp client:

enter number 1 :2 come in number 2 :5 come in number 3 :4 come in number 4 :3 come in number 5 :1 select protocol: 1.udp 2.tcp 1 info sent server

my server shows this:

$ java udpserver udp server running waiting info client 2 1024 exception in thread "main" java.lang.numberformatexception: input string: "2" @ java.lang.numberformatexception.forinputstring(numberformatexception.java:65) @ java.lang.integer.parseint(integer.java:492) @ java.lang.integer.parseint(integer.java:527) @ udpserver.main(udpserver.java:49) $

what causing error? why string 2 not getting converted?

you have issue client code. however, simple workaround take first character of num1string:

int numbers2=integer.parseint(num1string.substring(0, 1));

java udp numberformatexception

No comments:

Post a Comment