Dovakin940
Dovakin940

Reputation: 63

java out of range in loop for

This code is working but ugly:

for ( int i = 0, l=1; i < word.length() && l < word.length(); i++, l++) {  
    char c = word.charAt(i);
    j = (int) c;
    char nextRank = word.charAt(l);
    k = (int) nextRank;
} 

I would like to change him to something like that :

for (int i = 0; i < word.length(); i++) {  
    char c = word.charAt(i);
    j = (int) c;
    char nextRank = word.charAt(i+1);
    k = (int) nextRank;
} 

This one returns an error: String index out of range. I understand why: when it comes to the last letter the "char nextRank = word.charAt(i+1);" has nothing left to do.

But I don't know how to fix this problem!

Upvotes: 3

Views: 141

Answers (6)

pap
pap

Reputation: 27614

How about

for (int i = 0; i < word.length() - 1; i++) {  

Upvotes: 2

Thinhbk
Thinhbk

Reputation: 2214

You just need to loop from 0 to word.length() -1.

        for (int i = 0; i < word.length() - 1; i++) {  
            char c = word.charAt(i);
            j = (int) c;
            char nextRank = word.charAt(i+1);
            k = (int) nextRank;
        } 

Upvotes: 0

Ahmad
Ahmad

Reputation: 12737

Just decrease the limit of i by 1

for (int i = 0; i < word.length()-1; i++) {  
            char c = word.charAt(i);
            j = (int) c;
            char nextRank = word.charAt(i+1);
            k = (int) nextRank;
        } 

Upvotes: 0

Esailija
Esailija

Reputation: 140228

int length = word.length() - 1;
for (int i = 0; i < length; i++) {
    char c = word.charAt(i);
    j = (int) c;
    char nextRank = word.charAt(i + 1);
    k = (int) nextRank;
}

Upvotes: 1

Amit Deshpande
Amit Deshpande

Reputation: 19185

Start i from 1

for (int i = 1; i < word.length(); i++) {  
        char c = word.charAt(i-1);
        j = (int) c;
        char nextRank = word.charAt(i);
        k = (int) nextRank;
    } 

Upvotes: 3

Patient: "It hurts when i do this under that condition"

Doctor: "Well, then if that condition is met, don't do that"

if(i+1 < word.length)
{
    char nextRank = word.charAt(i+1);
    ...

Upvotes: 2

Related Questions