我正在尝试使用套接字来接收消息 执行此代码时,我得到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();
}
}
}
此例外:
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)
答案 0 :(得分:1)
我仍然不太确定套接字上收到的消息是什么。以下内容将接受client : number
表单上的消息以及仅包含该号码的消息。确定这是否是你需要的。
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);
}
答案 1 :(得分:0)
您必须逐个转换输入字符串的数字。 然后你可以分开它们。