【发布时间】:2014-04-07 05:26:27
【问题描述】:
我正在尝试从转换为字符数组的字符串输入中计算 ASCII 字符的频率。
我尝试实现来自this 线程的已接受答案,以及我的代码以在 3 列表中打印结果。
package com.mypackage.mp;
import java.util.*;
public class AsciiCounter {
public static void displayAsciiOccurrence(String inputWords) {
int[] iaCount = new int[256]; //this
char[] caInputWords = inputWords.toCharArray();
int i = 0;
for(i = 0; i < caInputWords.length; i++) {
iaCount[caInputWords[i]]++;
}
// Print table
System.out.println("\nDEC\tASCII\tFREQ");
for(int ctr = 0; ctr < 256; ctr++) {
System.out.println(ctr +"\t" + (char) (ctr) + "\t" + iaCount[caInputWords[i]]); //this
}
}
public static void main(String[] args) {
String inputWords = null;
Scanner scn = new Scanner(System.in);
System.out.print("Enter words: ");
inputWords = scn.nextLine();
displayAsciiOccurrence(inputWords); //this
scn.close();
}
}
但是,它返回一个ArrayIndexOutOfBoundsException。我想要的输出应该是:
Enter words: AA bC! d
DEC ASCII FREQ
0
.. .. ..
32 2
33 ! 1
.. .. ..
65 A 2
66 B 0
67 C 1
..
98 b 1
99 c 0
100 d 1
..
255
(.. 属于介于两者之间的任何内容,并且必须打印 0 作为频率。)
堆栈跟踪:
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 8 在 com.mypackage.mp.AsciiCounter.displayAsciiOccurrence(AsciiCounter.java:20) 在 com.mypackage.mp.AsciiCounter.main(AsciiCounter.java:31)
【问题讨论】:
-
你能在你得到那个异常的那一行添加吗?谢谢。
-
您能否编辑您的问题以添加完整的堆栈跟踪?
-
请注意,
.toCharArray()基本上会“复制”字符串中的所有字符;您可能想改用String的.charAt()。 -
已编辑问题以包含堆栈跟踪。感谢您的帮助。
标签: java arrays for-loop ascii indexoutofboundsexception