wjhplano
wjhplano

Reputation: 591

javascript while loop doesn't end

I'm trying to run the following while loop in JavaScript:

function returnSubstring(i, theString) {
    var j = 1;
    while (i > 1) {
        if (theString.charCodeAt(j) == ',') {
            i--;
        }
        else {
            <% System.out.println("nope, not a comma"); %>
        }
        j++;
    }
    var value = theString;
    var subString = value.substring(j, value.indexOf(",", j+1));
    alert(subString);       
}

and I just pass an index and string

returnSubstring(someIndex, someString);

It keeps crashing. I think i atleast get one round in the while loop. (I get 1 'nope') What am I doing wrong here?

also when index is 0 or 1 it works. but other numbers, no

Upvotes: 0

Views: 1690

Answers (4)

Goodwine
Goodwine

Reputation: 1718

You should ALWAYS decrement i, otherwise you will never end your loop, and J will be out of bounds. Also... you should var j = 0, otherwise you will skip the first character.

For example: "Text", and i == 2

You start at:
"T", no comma, move j forward, i still 2.
"e", no comma, move j forward, i still 2.
"x", no comma, move j forward, i still 2.
"t", no comma, move j forward, i still 2.
""(empty string), no comma, j is now out of bounds, move j forward, i still 2.
^ This last step gets repeated forever.

Instead, change your code to:

function returnSubstring(i, theString) {
    i = i > theString.length() ? theString.length() : i; // don't go too far.
    var j = 0; // Start at 0
    while (i >= 1) { // `i > 1` is stopping the code 1 character earlier
        if (theString.charCodeAt(j) != ',') { // this `if` is not required
            console.log("nope, not a comma"); // No JAVA code, please
        }
        i--;
        j++;
    }
    var value = theString;
    var subString = value.substring(j, value.indexOf(",", j+1));
    // alert(subString); // not necessary
    return subString; // return the value
}

Upvotes: 1

Vladimir Shtokman
Vladimir Shtokman

Reputation: 169

I suggest that your loop iterates through the input string, something like this:

for(var i = 0; i < theString.length; i++) { ... }

That would prevent a number of logical errors that would result in an infinite loop.

Upvotes: 0

You should decrement i

Are you sure you can do this:

<% System.out.println("nope, not a comma"); %>

Why don't you use:

document.write()

Upvotes: 1

Njol
Njol

Reputation: 3279

You don't decrement i if the character at i is not a comma. I recommend to use a for loop so that i gets decremented no matter what's in the loop: for (; i > 1; i--)

Upvotes: 0

Related Questions