【问题标题】:StringIndexOutOfBoundsException with StringBuffer.CharAtStringIndexOutOfBoundsException 与 StringBuffer.CharAt
【发布时间】:2016-12-13 06:28:22
【问题描述】:

我现在正在尝试打印单词的后缀,但出现了一些问题。

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.StringBuffer.charAt(Unknown Source)
at _20161212.Launcher.compareSameThings(Launcher.java:67)
at _20161212.Launcher.main(Launcher.java:52)

这是错误代码:

我正在寻找原因,但对我来说很难。

这个

public static void compareSameThings(StringBuffer[] strbuf, int index01, int index02, int count) {
    count++;
    if ((int) strbuf[index01].charAt(count) > (int) strbuf[index02].charAt(count)) {
        StringBuffer temp = strbuf[index01];
        strbuf[index01] = strbuf[index02];
        strbuf[index02] = temp;
    } else if ((int) strbuf[index01].charAt(count) == (int) strbuf[index02].charAt(count)) {
        compareSameThings(strbuf, index01, index02, count);
    }
}

还有这个

for (int index01 = 0; index01 < str.length() - 1; index01++) {
    for (int index02 = index01 + 1; index02 < str.length(); index02++) {
        int count = 0;
        if ((int) strbuf[index01].charAt(count) > (int) strbuf[index02].charAt(count)) {
            StringBuffer temp = strbuf[index01];
                strbuf[index01] = strbuf[index02];
                strbuf[index02] = temp;
        } else if (strbuf[index01].charAt(count) == strbuf[index02].charAt(count)) {
                compareSameThings(strbuf, index01, index02, count);
        }
    }
}

您能告诉我出现这些问题的原因吗?

【问题讨论】:

标签: java string indexoutofboundsexception stringbuffer


【解决方案1】:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.StringBuffer.charAt(Unknown Source)
at _20161212.Launcher.compareSameThings(Launcher.java:67)
at _20161212.Launcher.main(Launcher.java:52)

意思是:

There was an Exception thrown. It's called StringIndexOutOfBoundsException and 
    the index which was out of bounds was 1
it was thrown in method charAt
in compareSameThings(Line 67th in Launcher.java)
in main(Line 52 in Launcher.java)

所以基本上,您尝试在索引 1 处获取字符,但没有这样的字符。这意味着,您的 StringBuffer 少于 2 个字符。

【讨论】:

    猜你喜欢
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2020-08-18
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2018-02-24
    相关资源
    最近更新 更多