Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java out of range in loop for

Tags:

java

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!

like image 915
Dovakin940 Avatar asked Aug 11 '26 23:08

Dovakin940


1 Answers

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;
    } 
like image 148
Amit Deshpande Avatar answered Aug 15 '26 13:08

Amit Deshpande



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!