gpt4 book ai didi

java.lang.ArrayIndexOutOfBoundsException : 26

转载 作者:行者123 更新时间:2023-12-03 00:57:52 26 4
gpt4 key购买 nike

我目前正在学习 Java,当我运行学习 Material 中的示例代码时,我得到了“线程“main”中出现异常 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 个字符长并且没有值就其一而言。

最佳答案

代码正在尝试从“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

关于java.lang.ArrayIndexOutOfBoundsException : 26,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com