calculate length of a string
Hello.
I have written a function to calculate the length of a string, it gives the wrong length can you help me fix the codes?
public int GetStringLength(String z)
{
int y = 1;
int x = 0;
while (1 > 0)
{
try
{
char m = z.charAt(y);
x = x + 1;
y = y + 1;
}
catch (Exception fini)
{
return x;
}
}
}
@Op.
Remove x, and return y -1, move the try catch out of the loop, and return after the catch block.
(Do also change from while (1 > 0) to while (true), it's easier to understand))
Kaj
kajbja at 2007-7-29 16:52:02 >

Firstly, there is already a String.length function available - so there is no need fo this function.
Secondly, you are initlizaing x to 0 and y to 1. charAt expects a zero based index into the string. I hope that should be fine to tell you where the problem is.
HTH.
> Firstly, there is already a String.length function
> available - so there is no need fo this function.
Method. We call them "methods".
~
> > Firstly, there is already a String.length
> function
> > available - so there is no need fo this
> function.
>
> Method. We call them "methods".
>
Maybe we shouldn't. Calling them functions would turn Java into a functional programming language, which is sure to apease some of the people who want to turn Java into something else by adding all kinds of nonsense "features" :)
> Maybe we shouldn't. Calling them functions would turn
> Java into a functional programming language, which is
> sure to apease some of the people who want to turn
> Java into something else by adding all kinds of
> nonsense "features" :)
;o)
~
> Hello.
> I have written a function to calculate the length of
> a string, it gives the wrong length can you help me
> fix the codes?
>
>public int GetStringLength(String z)
> {
> int y = 1;
> int x = 0;
> while (1 > 0)
> {
> try
> {
>char m = z.charAt(y);
> x = x + 1;
>y = y + 1;
>catch (Exception fini)
> {
>return x;
> }
Now that's what I call scratching ones belly by wrapping one's arm around one's backside until reaching the belly.