0

这就是我所拥有的,但它不起作用,这让我感到困惑。如果您向下滚动,我评论了某人发布了我遇到的确切问题以及我正在尝试做的事情。我在想也许问题是我生成随机字符的代码:

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;
}
4

3 回答 3

0

不知道是否还有其他错误,但您正在b从 0 到 26 进行迭代,并使用它作为count[]长度为 26 的索引。该数组具有从 0 到 25 的有效索引,您将IndexOutOfBoundsException在访问它时收到26.

它应该是:

...
for (int b = 0; b < 26; b++) 
...
于 2012-11-19T00:14:23.303 回答
0

不确定这是否是答案,因为我们不知道发生了什么。但这里有一些东西,你的 int[] 计数数组有 26 个索引,但你数到 27: for (int b = 0; b <= 26; i++) -> 这将产生 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

于 2012-11-19T00:16:59.303 回答
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]);
        }
    }
}
于 2013-01-07T17:41:52.677 回答