Problem about receiving data

Hi all,
I have written a program using Arduino Duemilanove to receive data (integers ranging from 0 - 500) sent from a computer via a wifi module. However, there are some problems . I open the serial monitor to observer the data received. However, i observed that sometimes the data received is correct, sometimes the data become -1.

The program are quoted below. There are some bytes added to the data for sending. The length of the data is at the 4th byte, the data sent will be starting at the 6th byte. For example, if the data is a 1 digit integer, the data is at the 6th byte. If the data is a 2 digit integer, the data is at the 6th byte and 7th byte etc. In the program, the data length (the 4th byte) will be read first.

If the data length is 1, the ascill code of the integer will be stored at variable val_z, If the data length is 2, the ascill code of the units digit will be stored at variable val_z nd that of the tens digit will be stored at variable val_y. If the data length is 3, the ascill code of the units digit will be stored at variable val_z nd that of the tens digit will be stored at variable val_y and the hundred digit will be stored at variable val_x.

int val_x,val_y,val_z;
int data_length;

void setup()
{
}

void loop()
{
Serial.begin(115200);

if(Serial.available()>0)
{
for(int i=0;i<4;i++)
{
data_length = Serial.read();
}

for(int j=0;j<data_length+1;j++)
{
val_z = Serial.read();

if(data_length==1)
{
val_y = 0;
val_x = 0;
}

if(data_length==2)
{
if(j==1) val_y = val_z;
val_x = 0;
}

if(data_length==3)
{
if(j==1) val_x = val_z;
if(j==2) val_y = val_z;
}

}

Serial.println(val_x);
Serial.println(val_y);
Serial.println(val_z);

Serial.flush();
Serial.end();

}

}

Can anyone help?

if(Serial.available()>0)
 {
   for(int i=0;i<4;i++)
   {
       data_length = Serial.read();
   }

Imagine that here, "Serial.available" returns 1.
For reference, your second "Serial.read" will occur a few hundred nanoseconds after the first.
You may want to compare this timescale with your serial bit-rate.

(for another clue, have a look at the documentation for "Serial.read")

Thanks Groove!
after adding a delay when reading data, i have solved the problem ;D

after adding a delay when reading data, i have solved the problem

...until you change the serial rate.
Why not fix it properly, using "available()"?

   for(int i=0;i<4;i++)
   {
       data_length = Serial.read();
   }

What is the purpose of looping 4 times, overwriting the same value each time?

after adding a delay when reading data, i have solved the problem

As Groove points out, no, you haven't. You've masked it.