【发布时间】:2018-05-15 12:18:02
【问题描述】:
请忽略错误的文件名,但到目前为止我就是这样做的。我想计算Java 文件中的所有ASCII 字符,但它得到一个带有大文本的“数组越界错误”
此代码:
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
我做错了什么?
【问题讨论】:
-
请添加完整的堆栈跟踪。
-
鉴于
char is defined as Unicode character, which implies 16 bits unsigned为什么你的范围是 256? -
你为什么使用
DataInputStream?您应该只使用DataInputStream来读回最初使用DataOutputStream写入的文件!只需使用普通的“FileInputStream”即可。 -
count是 256 个元素,但count[y]++使用输入文件中的char的值进行索引。chars 的值最高可达 65,536,因此您很容易受到ArrayIndexOutOfBoundsException的影响。 -
那是您文本中正确的单引号字符。
标签: java arrays exception counter