我有一个字符串= “1.515 53.11 612.1 95.1 0 0 0 0” 我特林通过这个代码解析它:用分隔符分析字符串“;” (JAVA)
public class SendThread implements Runnable {
public void run()
{
socket = null;
BufferedReader in;
while (true)
{
// Loop until connected to server
while (socket == null){
try{
socket = new Socket ("192.168.137.1", 808);
}
catch (Exception e) {
socket = null;
//Log.d("Connection:", "Trying to connect...");
}
try {
Thread.sleep(30);
} catch (Exception e) {}
}
// Get from the server
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Connection: ", "connected");
String line = null;
while ((line = in.readLine()) != null) {
Log.d("Socket:", line);
NumberFormat nf = new DecimalFormat ("990,0");
String[] tokens = null;
String[] tempData = null;
String[] windData = null;
try {
tokens = line.split(";");
tempData = tokens[0].trim().split(" ");
windData = tokens[1].trim().split(" ");
} catch (Exception error)
{
Log.d("Parsing error:", error+"");
}
for (int i = 0; i < currentTemp.length; i++)
currentTemp[i] = (Double) nf.parse(tempData[i]);
for (int i = 0; i < currentWind.length; i++)
currentWind[i] = (Double) nf.parse(windData[i]);
//Toast.makeText(getApplicationContext(), "Received data:", duration)
for (int i = 0; i < currentTemp.length; i++){
Log.d("Converted data: currentTemp["+i+"] = ", currentTemp[i]+"");
}
for (int i = 0; i < currentWind.length; i++){
Log.d("Converted data: currentWind["+i+"] = ", currentWind[i]+"");
}
}
socket = null;
Log.d("Connection: ", "lost.");
}
catch (Exception e) {
socket = null;
Log.d("Connection: ", "lost.");
Log.d("Connection:", e+"");
}
}
}
}
错误代码:(但我不知道更好的方法来保持套接字连接:)
我总是得到“java.text.ParseException:Unparseable number”。如何解决它?
令牌,TempData的,windData都是String []
您报告的错误未由您发布的代码生成。 – cherouvim
你确定这就是你正在做的?我将代码放在一起,没有错误。此外,似乎你在试图解析数字时遇到了这种例外情况,这不在你提供的代码 –
中,你应该发布一个更大的代码段,除了\\;问题,我们仍然在猜测 – soulcheck