Java错误中的Ascii字符计数器

时间:2018-05-15 12:18:03

标签: java arrays exception counter

请忽略错误的文件名,但这是我到目前为止所做的。我想计算ASCII中文件中的所有Java个字符,但是大文本会出现“数组越界错误”

此代码:

class CreateZipFile {


    public static void main(String[] args) {
            try {
                CharacterCounter();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println(e.getClass().getSimpleName() + "-" + e.getMessage());//Throws nice output message 

            }
    }

        private static void CharacterCounter() throws IOException{

        FileInputStream fstream = new FileInputStream("/Users/Devonte1/Desktop/Javatest.txt");//Read in file

        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));//Take file stream and place it into bufferedReader
        OutputStreamWriter bw = null;

        String strLine="";
        String removeSpace="";
        while ((strLine = br.readLine()) != null) {

            removeSpace+=strLine;
        }

        String st=removeSpace.replaceAll(" ", "");//Replace all spaces 
        char[]text = st.toCharArray();//Create new conjoined character array
        System.out.println("Character Total");

        int [] count = new int [256];//Character array

        //Create index 
            for(int x = 0; x < 256; x ++){
                    count[x]=0;
            }

        //Search file 
        for (int index = 0; index < text.length; index ++) {
             char ch = text[index];
             int y = ch;
             count[y]++;
        }

        //
        for(int x = 0; x < 256; x++){
            char ch= (char) x;
            if (count[x] == 0){ 
                System.out.println("Character not used"+ " "+ ch + " = (char code " + (int) ch + ")");
            }
            else if (count[x] != 0){
                System.out.println("Character " + ch + " used" + count[x] + " = (char code " + (int) ch + ")");
            }
        }

        }

}

错误:

Error:Arrayoutofboundexception: 8217

我做错了什么?

1 个答案:

答案 0 :(得分:1)

解决方案1 ​​

统计所有65,535个字符的统计信息。 需要将 count 数组的大小更改为长度为65,535:

int [] count = new int [65535];  // Character array

// Create index 
for (int x = 0; x < 65535; x ++){
  count[x] = 0;
}

在打印统计信息时,最后一部分也会更改256到65535。

解决方案2

仅对序数值小于256的字符计算统计信息:

// Create index 
for(int x = 0; x < 256; x ++){
  count[x] = 0;
}

// Search file 
for (int index = 0; index < text.length; index ++) {
  char ch = text[index];
  int y = ch;
  if (y < 256)
    count[y]++;
}