I'm trying to parse information from a temperature sensor. Sensors sends a String with the format:
Temp: 1 388 2 358 3 200?
Temp: 1 388 2 200? 3 200?
(First String contains a valid channel 2 sample and channel 3 disconnected, and second String has channel 2 and 3 disconnected).
I need to parse those "dat" which is a float without the dot, and I cant use String.split() because if the sensor doesn't detects anything it adds a '?' to the end of "dat". Output should be:
Temp[0]= 38.8
Temp[1]= 35.8
Temp[2]= 20.0
Also I need to parse that '?' to say if a channel it's disconnected.
I try to use split() to solve this problem, and did't see anything wrong you say.
public static void parseData(String data) {
String[] args = data.split("\\s+");
for (int i=2; i<7; i+=2) {
if (args[i].charAt(args[i].length() - 1) == '?') {
args[i] = args[i].substring(0, args[i].length() - 1);
}
double val = Double.parseDouble(args[i]) / 10;
System.out.println("Temp[" + (i-1)/2 + "]= " + val);
}
}
Probably the most easy approach would be to use String.split("\\\\s")
this will provide an array of Strings. For example:
Temp: 1 388 2 358 3 200? => {"Temp:", "1", "388", "2", "358", "3", "200?"}
Knowing that the first temperature should be the 3rd column you can start processing from there. For obtaining numeric values you can use Integer.parse(...)
. For floats you can divide by 10. You can check whether it has a trailing "?" with String.endsWith(...)
. For more complicated processing you can use different regexs. More information here and here about regex in java.
How do you receive your input? Where do you read it from? A good and simple solution could be the scanner .
Here you go:
Scanner line = new Scanner(sensorStream);
while (line.hasNext()) {
line.next(); // Temp:
line.next(); // #
int firstReading = line.nextInt(); // 388
float realFirstReading = firstReading/10.0; // 38.8
line.next(); // #
int secondReading = line.nextInt(); // 358
float realSecondReading = secondReading/10.0 // 35.8
line.next(); // #
int thirdReading = line.nextInt(); // 200
float realThirdReading = thirdReading / 10.0; // 20.0
// do what you will with it
}
If you need further help, do leave a comment...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.