字符串索引超出范围 [英] String index out of range

查看:374
本文介绍了字符串索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让这个程序计算连续字符的数量
并且我得到的错误是:字符串索引超出范围。任何人都可以帮我
修复此问题吗?

Im trying to make this program to count the number of consecutive characters and im getting the error that says :"String index out of range." Can anyone help me fix this?

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?

The last element in your loop is 100% guaranteed to cause a problem. Perhaps only go to the length - 1 in your loop?

考虑代码:

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]!!

这篇关于字符串索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆