java - Java 中的字符串索引超出范围

标签 java

我正在尝试让这个程序计算连续字符的数量 我收到错误消息:

"String index out of range."

import javax.swing.*;

public class Project0 {
    public static void main(String[] args){

        String sentence;
        sentence = JOptionPane.showInputDialog(null, "Enter a sentence:"); /*Asks the user to
                                                                             enter a sentence*/
        int pairs = 0;
        for (int i = 0; i < sentence.length(); i++){     //counts the pairs of consecutive characters
            if ( sentence.charAt(i) == sentence.charAt(i+1)) pairs++;
        }

        JOptionPane.showMessageDialog(null, "There were " + pairs + " pairs of consecutive characters");
    }//main
}// Project0

最佳答案

循环中的最后一个元素 100% 肯定会导致问题。也许只转到循环中的长度 - 1?

考虑代码:

for (int i = 0; i < sentence.length(); i++){
    if ( sentence.charAt(i) == sentence.charAt(i+1)) pairs++;
}

String s = "AABBCC";

first loop, i = 0 : compare s[0] to s[1]
first loop, i = 1 : compare s[1] to s[2]
first loop, i = 2 : compare s[2] to s[3]
first loop, i = 3 : compare s[3] to s[4]
first loop, i = 4 : compare s[4] to s[5]
first loop, i = 5 : compare s[5] to s[6] // WOAH, you can't do that! there is no s[6]!!

关于java - Java 中的字符串索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5011866/

相关文章:

java - 需要 isFlush 和 isThreeKind 方法、扑克类型程序的一些帮助

java - jackson 解码 : store inner xml as string

Java 关于@Override

java - Jackson——使用 xpath 或类似工具解析 json

java - 在 Java 泛型类中,在构造函数级别添加额外的泛型约束?

java 类属性带有 getter 和 setter,这不应该很常见吗

java - 如果找到字符,则忽略字符后的字符串

io - 为什么java不能读取rt.jar?

java - 适用于 Android 的适当多任务处理

java - 如何做 "massive"作业调度( quartz ?)