Reputation: 7
I am trying to receive message using socket
When Executing this code i am getting NumberFormatException
public class ThreadSocket extends Thread {
Socket socket;
int k;
ThreadSocket(Socket socket) {
this.socket = socket;
}
public void run() {
try {
String message = null;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((message = bufferedReader.readLine()) != null) {
System.out.println("Incomming message client : " + message);
k += Integer.parseInt(message);
System.out.println("la somme est :" + k);
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This Exception :
Exception in thread "Thread-0" java.lang.NumberFormatException: For input string: "3 : 2"
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 ThreadSocket.run(ThreadSocket.java:33)
Upvotes: 0
Views: 870
Reputation: 86276
I am still not quite sure what the possible messages received on the socket are. The following will accept messages on the form client : number
as well as messages containing only the number. Decide if this is what you need.
while ((message = bufferedReader.readLine()) != null) {
System.out.println("Incomming message client : " + message);
// is there a colon followed by a space in the message?
final String delimiter = ": ";
int indexOfColon = message.lastIndexOf(delimiter);
if (indexOfColon == -1) { // no, no colon and space in message
// try to use entire message
k += Integer.parseInt(message);
} else { // yes
// take out the part after the colon and space and try parsing it as an integer
int number = Integer.parseInt(message.substring(indexOfColon + delimiter.length()));
k += number;
}
System.out.println("la somme est :" + k);
}
Upvotes: 1
Reputation: 1
You have to cast the numbers of your input String one by one. and Then you can divide them.
Upvotes: 0