Click to See Complete Forum and Search --> : Function not working as it should


FunctionedOut
June 5th, 2004, 12:27 AM
Hello All

I have written this function which is supposed to:
return true if a string consists of a sequence of six digits otherwise it returns false.

My problem is when I put 1234c5 to test the function (or any other string which contains a alphabetical character), it returns true and not false, which it should be returning..



function check(aString)
{

if (aString.length !=6)
{
return false
};
for (var i=0; i<6; i++)
{
if (!isNumeric(aString.charAt(i)))
{
return false
}
else
{
return true
}
};
}



Can anyone help me deduce where I am going wrong with this. I know I can place the last return statement outside the for loop but I really would like to know why this code is not working as it should. It's driving me crazy. :mad: Any suggestions?

Thank you.

atif_ilm
June 5th, 2004, 01:34 AM
Originally posted by FunctionedOut
Hello All

I have written this function which is supposed to:
return true if a string consists of a sequence of six digits otherwise it returns false.

My problem is when I put 1234c5 to test the function (or any other string which contains a alphabetical character), it returns true and not false, which it should be returning..



function check(aString)
{

if (aString.length !=6)
{
return false
};
for (var i=0; i<6; i++)
{
if (!isNumeric(aString.charAt(i)))
{
return false
}
else
{
return true
}
};
}









What is happening that your for loop will just run for once in "1234c5" it will pick up 1and will check if it is numeric yes it is numeric so it will return true and that's it.

A correct code might be like this




function check(aString)
{

if (aString.length !=6)
{
return false
};
for (var i=0; i<6; i++)
{
if (!isNumeric(aString.charAt(i)))
{
return false
}

};
return true;
}

FunctionedOut
June 5th, 2004, 08:39 AM
Originally posted by atif_ilm
What is happening that your for loop will just run for once in "1234c5" it will pick up 1and will check if it is numeric yes it is numeric so it will return true and that's it.


Thanks Atif_ilm

I knew the solution to the code, I just could not see why as it stood, the code was giving out an incorrect response.

Thanks very much for clearing that up.