我有一個字符串= 「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