计算数组中出现的字符数

时间:2012-11-18 23:42:03

标签: java arrays for-loop

这就是我所拥有的,但它不起作用,这对我来说很困惑。如果你向下滚动,我评论某些人发布我遇到的确切问题以及我想要做什么。我想也许问题是我的代码生成随机字符:

public void add (char fromChar, char toChar){
    Random r = new Random(); //creates a random object
    int randInt;
    for (int i=0; i<charArray.length; i++){
        randInt = r.nextInt((toChar-fromChar) +1);
        charArray[i] = (char) randInt; //casts these integers as characters
    }
}//end add
public int[] countLetters() {
int[] count = new int[26];
char current;

     for (int b = 0; b <= 26; b++) {
         for (int i = 97; i <= 123; i++) {
             char a = (char) i;
             for (int ch = 0; ch < charArray.length; ch++) {
                 current = charArray[ch];
                if (current == a) {
                count[b]++;
                }
             }
         }
     }
return count;
}

3 个答案:

答案 0 :(得分:0)

不知道是否存在其他错误,但是您正在从0到26迭代b并将其用作长度为26的count[]的索引。此数组具有0的有效索引当包含26时,您将收到IndexOutOfBoundsException

应该是:

...
for (int b = 0; b < 26; b++) 
...

答案 1 :(得分:0)

不确定这是否是答案,因为我们不知道发生了什么。 但是这里有一些东西,你的int [] count数组有26个索引,但是你要数到27: for(int b = 0; b&lt; = 26; i ++) - &gt;这将导致27个指数。 试试吧:

public int[] countLetters() {
    int[] count = new int[26];
    char current;

    for (int b = 0; b < 26; b++) {
        for (int i = 97; i < 123; i++) {
            char a = (char) i;
            for (int ch = 0; ch < charArray.length; ch++) {
                current = charArray[ch];
                if (current == a) {
                    count[b]++;
                }
             }
         }
     }
    return count;
}

小错误,谢谢Fabian

答案 2 :(得分:0)

这是你想要的:

这是文件charCounter.java

import java.util.*;
import java.awt.*;

public class charCounter
{
    char[] charArray = new char[50];
    int randInt;
    Random r = new Random();

    public charCounter()
    {}

    public void create ()
    {
            for (int i=0; i<charArray.length; i++)
        {
                randInt = 97+r.nextInt(26);
                charArray[i] = (char) randInt; //casts these integers as characters
            }
    }

    public void printCharArray()
    {
        for(int i=0; i<charArray.length; i++)
        {
                System.out.println(charArray[i]);
        }
    }

    public int[] countLetters() 
    {
        int[] count = new int[26];
        int index = 0;
            for(int i=0; i<charArray.length; i++)
        {
            index = ((int)charArray[i])-97;
            count[index]++;
        }
        return count;
    }
}

这是我制作的驱动程序:

public class driver
{
    public static void main(String args[])
    {
        charCounter c = new charCounter();
        int[] printThis;

        c.create();
        printThis = c.countLetters();

        for(int i=0; i<printThis.length; i++)
        {
            System.out.println(printThis[i]);
        }
    }
}