Reputation: 63
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
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
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
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
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
Reputation: 31204
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