这段代码很有效但很难看:
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;
}
我想把他变成这样的东西:
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;
}
这一个返回错误:String index out of range
。我理解为什么:当谈到最后一个字母时,&#34; char nextRank = word.charAt(i + 1);&#34;没有什么可做的。
但我不知道如何解决这个问题!
答案 0 :(得分:3)
从i
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;
}
答案 1 :(得分:2)
病人:“当我在这种情况下这样做时会感到疼痛”
医生:“好吧,那么如果满足这个条件,就不要这样做”
if(i+1 < word.length)
{
char nextRank = word.charAt(i+1);
...
答案 2 :(得分:2)
怎么样
for (int i = 0; i < word.length() - 1; i++) {
答案 3 :(得分:1)
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;
}
答案 4 :(得分:0)
将i的限制减少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;
}
答案 5 :(得分:0)
你只需要从0循环到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;
}