【问题标题】:Alphabetic Counter utilizing string arrays利用字符串数组的字母计数器
【发布时间】:2013-07-15 20:04:50
【问题描述】:
public class AssignmentChapter9
{
    public static void main(String[] args)
    {
        String words = Input.getString("Please enter a series of words with the spaces omitted.");
        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        String inputWords = words.toLowerCase();
        int lcount[] = new int[26];
        char var1;
        char var2;

        for(int x = 0; x <= words.length(); x++)
        {
            var1 = words.charAt(x);

            for(int y = 0; y < 27; y++)
            {
                var2 = alphabet.charAt(y);

                if(var1 == var2)
                {
                    lcount[y] += 1;
                }

            }
        }

        for(int z = 0; z < 27; z++)
        {
            System.out.println("Letter " + alphabet.charAt(z + 1) + " count = " + lcount[z]);
        }
    }
}

我一直在尝试用 java 编写一个程序来确定字母表中每个字符在给定字符串中出现的次数。我能够成功编译程序,但是在用户输入完成后,它给出了一个越界异常。任何帮助将不胜感激。

【问题讨论】:

    标签: arrays string counter indexoutofboundsexception alphabet


    【解决方案1】:

    在最后一个循环中,您从 0 迭代到 27,并且您尝试访问无法工作的索引 z + 1,因为您的字母表只有 26 个索引 - 正确的只有 z。所以正确的代码是:

    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    String inputWords = words.toLowerCase();
    int lcount[] = new int[26];
    char var1;
    char var2;
    
    for(int x = 0; x < words.length(); x++)
    {
        var1 = words.charAt(x);
        for(int y = 0; y < alphabet.length(); y++)
        {
            var2 = alphabet.charAt(y);
            if(var1 == var2)
            {
                lcount[y] += 1;
            }
        }
    }
    
    for(int z = 0; z < alphabet.length(); z++)
    {
        System.out.println("Letter " + alphabet.charAt(z) + " count = " + lcount[z]);
    }
    

    当你迭代数组或列表时,使用 length 方法,不要使用常量!每当您使用例如扩展您的字母表时!?+- 您的代码将不再工作。 length 方法保护您的代码不会出现index out of bound 错误。

    您还可以使用for each loop 构造来节省一些代码行并使代码更具可读性:

    String alphabet = "abcdefghijklmnopqrstuvwxyz";
    int lcount[] = new int[26];
    
    for (char character : words.toLowerCase().toCharArray())
    {
        for(int y = 0; y < alphabet.length(); y++)
        {
            if(character == alphabet.charAt(y))
            {
                lcount[y] += 1;
            }
        }
    }
    
    for(int z = 0; z < alphabet.length(); z++)
    {
        System.out.println("Letter " + alphabet.charAt(z) + " count = " + lcount[z]);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多