We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Problem parsing integer from string
Page Index Toggle Pages: 1
Problem parsing integer from string (Read 224 times)
Problem parsing integer from string
Feb 16th, 2009, 7:44pm
 
I am trying to parse integers from a comma delimited string received via serial port.
the strings look like so: "1500,364" and are terminated with a linefeed.

This is the code that receives and parses the strings:
void serialEvent(Serial p) {
 int delimIndex = -1;
 inString = (myPort.readString());
 delimIndex = inString.indexOf(',');
 if (delimIndex != -1) {
   posString = inString.substring(0, delimIndex);
   disString = inString.substring(delimIndex+1, inString.length()-1);
   try {
     servoPos = int(posString);
     distance = int(disString);
     //servoPos = Integer.parseInt(posString);
     //distance = Integer.parseInt(disString);
   } catch(Exception e) {
     //do nothing
     println(e);
   }
   inString = "pos: " + posString + "| dis: |" + disString + "|";
 }
}

servoPos is parsed successfully from posString, but distance is not parsed from disString.

when I was using the Integer.parseInt() command to try to parse the integers, it worked for posString but threw a java.lang.NumberFormatException for disString. Using int() works for posString but fails (without throwing an exception) for disString.

Please let me know what I am doing wrong when I parse disString.

Thanks,

Cory
Re: Problem parsing integer from string
Reply #1 - Feb 16th, 2009, 8:51pm
 
Ummm...

Nevermind.

I figured it out. I forgot for a moment that .length() returns the length of the string, and since the string is zero-indexed then inString.length()-1 is actually the location of the linefeed character. changing the substring termination to inString.length()-2 fixed the problem.
Page Index Toggle Pages: 1