【问题标题】:Index out of bounds error. Why?索引超出范围错误。为什么?
【发布时间】:2015-09-12 19:08:17
【问题描述】:

我不明白为什么这种方法不起作用。它可以编译,但会引发运行时错误。

这是代码。这是一个猪拉丁化器。它应该将短语拆分为单词,然后格式化这些单词,然后将它们全部重新组合到一个 ArrayList 中(我以后可能会更改它。)我不明白为什么它运行不正确。

import java.util.*;
public class OinkerSpine 
{
    public ArrayList<String> pigLatin (String phrase)
    {
        phrase = phrase.replaceAll(".", " .");
        phrase = phrase.replaceAll(",", " ,");
        phrase = phrase.replaceAll("!", " !");
        //phrase = phrase.replaceAll("?", " ?");
        phrase = phrase.replaceAll("'", " '");

        String []words = phrase.split(" ");
        ArrayList <String> Endphrase = new ArrayList <String> ();
        final String AY = "ay";
        final String YAY = "-yay";

        String endword = "";

        for(int i=0; i < words.length; i++) 
        {
            String firstletter;
            String restofword;
            String secondletter;

            if (words[i].length() == 1)
            {
                firstletter = words[i];
                restofword = "";
            }
            else
            {
                firstletter = words[i].substring(0, 1);
                restofword = words[i].substring(1);
            }

            boolean firstIsUpper = (firstletter.equals(firstletter.toUpperCase()));

            if (firstIsUpper)
            {
                firstletter = firstletter.toLowerCase();
                secondletter = restofword.substring(0, 1);
                restofword = restofword.substring(1);

                secondletter = secondletter.toUpperCase();
                restofword = secondletter + restofword;
            }

            if (firstletter.equals("a") || firstletter.equals("e") ||
                firstletter.equals("i") || firstletter.equals("o") ||
                firstletter.equals("u"))
            {
                endword = firstletter + restofword + YAY;
            }

            else
            {
                endword = restofword + "-" + firstletter + AY;
            }

            endword = endword.replaceAll(" .", ".");
            endword = endword.replaceAll(" ,", ",");
            endword = endword.replaceAll(" !", "!");
            //endword = endword.replaceAll(" ?", "?");
            endword = endword.replaceAll(" '", "'");

            Endphrase.add(endword);
        }
        return Endphrase;
    }
}

这里有什么?

【问题讨论】:

标签: java string indexing


【解决方案1】:

如果restofwordword[i] 是空字符串会发生什么

secondletter = restofword.substring(0, 1);

firstletter = words[i].substring(0, 1);

【讨论】:

    【解决方案2】:

    您可能在这里替换了太多字符:

    phrase = phrase.replaceAll(".", " .");
    

    substring 的字母不足。你可能想要

    phrase = phrase.replaceAll("\\.", " .");
    

    或更好

    phrase = phrase.replace(".", " .");
    

    【讨论】:

    • 您的链接显示错误是由于在空字符串上执行子字符串引起的。
    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 2016-08-22
    • 2015-11-05
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多