我收到一个数据包,例如
"c~ ¹" M:0013A20040559361 Ax:48 Ay:10 Az:1012 Tp:25 B:45 ? Tm:Wednesday, 02/01/13 - 16:16.57 Sº~"
和其他无法粘贴的字符。我必须阅读冒号后面的值。例如,M: , Ax:, Ay:
将其存储或绘制在图表中。我知道两种方法:StreamTokenizer 或简单的 java 逻辑。问题是我都尝试过,但在读取值时仍然收到太多错误。另外,我尝试了一个字符串垃圾收集器,它也不起作用。
以下是两者的代码:
if(message2.contains("Ax:"))
{
int index = message2.indexOf("Ax:");
String Ax = message2.substring(index+3);
ChartAcceleration.tsAx.addOrUpdate(new Millisecond(), Double.valueOf(Ax));
}
StreamTokenizer Code:
StreamTokenizer st = new StreamTokenizer(
new StringReader(message));
boolean eof = false;
while(st.nextToken() != StreamTokenizer.TT_EOF){
int token = st.nextToken();
switch (token) {
case StreamTokenizer.TT_WORD:
String word = st.sval;
if(word.contains("Ax"))
{
Ax = true;
}
else
if(word.contains("Ay"))
{
Ay = true;
}
else
if(word.contains("Az"))
{
Az = true;
}
else
if(word.contains("P"))
{
P = true;
}
else
if(word.contains("B"))
{
B = true;
}
else
if(word.contains("Tp"))
{
Tp = true;
}
else
{
Ax = false;
Ay = false;
Az = false;
P = false;
B = false;
Tp = false;
}
// System.out.println("Word: " + word);
break;
case StreamTokenizer.TT_NUMBER:
double number = st.nval;
if(Ax)
{
Ax = false;
// errorChecker(AxStr,number);
AxStr = number;
Sender.publishAccelerator("Ax:" + String.valueOf(AxStr));
}
else
if(Ay)
{
Ay = false;
AyStr = number;
Sender.publishAccelerator("Ay:"+String.valueOf(AyStr));
}
else if(Az)
{
Az = false;
AzStr = number;
Sender.publishAccelerator("Az:"+String.valueOf(AzStr));
// System.out.println("Az:"+AzStr);
}
else
if(P)
{
P = false;
PStr = number;
Sender.publishPressure(String.valueOf(PStr));
//System.out.println("P:"+PStr);
}
else
if(B)
{
B = false;
BStr = number;
Sender.publishBattery(String.valueOf(BStr));
}
else
if(Tp)
{
Tp = false;
TpStr = number;
Sender.publishTemp(String.valueOf(TpStr));
}
break;
default:
}
}