我目前正在学习Java,当我从学习材料中运行示例代码时, “线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:26”
package com.java24hours;
public class Wheel {
public static void main(String[] arguments) {
String phrase[] = {
"A STITCH IN TIME SAVES NINE",
"DON'T EAT YELLOW SNOW",
"EVERY GOOD BOY DOES FINE",
"I WANT MY MVT",
"PLAY IT AGAIN, SAM",
"FROSTY THE SNOWMAN",
"ONE MORE FOR THE ROAD",
"HOME FIELD ADVANTAGE",
"SHEFFIELD WEDNESDAY",
"GOVER CLEAVLAND OHIO",
"ZELDA: MAJORAS MASK",
"SPEGHETTI WESTERN",
"TEEN TITANS GO",
"IT'S A WONDERFUL LIFE",
};
int [] letterCount = new int [26];
for(int count = 0; count < phrase.length; count++) {
String current = phrase[count];
char[] letters = current.toCharArray();
for(int count2 = 0; count2 < letters.length; count2++) {
char lett = letters[count2];
if ( (lett >= 'A') & (lett <= 'Z')) {
letterCount[lett - 'A']++;
}
}
}
for (char count = 'A'; count <= 'z'; count++) {
System.out.print(count + ": " +
letterCount [count - 'A'] + " ");
if (count == 'M') {
System.out.println();
}
}
System.out.println();
}
}
就程序而言,我得到的输出正确,但是我不确定为什么会出现异常。
通过阅读其他线程,我知道对于Java,数组以“ 0”开头,当我尝试将“ 26”更改为“ 25”时,它将导致程序无法运行。我想知道我得到的异常是否确实是一个问题,或者是Java告诉我该数组有未使用的部分,因为该数组实际上正在读取它应该为27个字符长且没有值一个。
答案 0 :(得分:4)
代码正在尝试从“ A”到“ z”。您需要从'A'到'Z'检查ASCII TABLE
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " +
letterCount [count - 'A'] + " ");
if (count == 'M') {
System.out.println();
}
}
进行此更改后,输出将为
A: 22 B: 1 C: 2 D: 12 E: 31 F: 8 G: 6 H: 7 I: 15 J: 1 K: 1 L: 10 M: 9
N: 18 O: 20 P: 2 Q: 0 R: 9 S: 16 T: 19 U: 1 V: 6 W: 7 X: 0 Y: 7 Z: 1
答案 1 :(得分:2)
问题出在count - 'A'
和您的范围:A - z
:
count
的值为A
时,您将访问索引0,没关系count
的值为Z
时,您将访问索引25,但仍然可以,但尚未绑定z
count
将值[
,您将尝试访问索引26
! 您需要在Z
停留
for (char count = 'A'; count <= 'Z'; count++) {
System.out.print(count + ": " + letterCount [count - 'A'] + " ");
// ...
}