3

这段代码有效但丑陋:

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。我明白为什么:当谈到最后一个字母时,“char nextRank = word.charAt(i+1);” 无事可做。

但我不知道如何解决这个问题!

4

6 回答 6

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;
    } 
于 2012-11-08T18:02:01.120 回答
2

怎么样

for (int i = 0; i < word.length() - 1; i++) {  
于 2012-11-08T18:04:20.763 回答
2

患者: “在那种情况下我这样做会很痛”

医生: “嗯,那如果符合条件,就不要那样做”

if(i+1 < word.length)
{
    char nextRank = word.charAt(i+1);
    ...
于 2012-11-08T18:01:51.047 回答
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;
}
于 2012-11-08T18:02:08.173 回答
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;
        } 
于 2012-11-08T18:02:58.890 回答
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;
        } 
于 2012-11-08T18:03:22.950 回答