运行Java全字母句判断代码报ArrayIndexOutOfBoundsException错误求解
问题原因
- 第一个错误:
temp数组初始化长度错误。你定义temp_count初始值为0,用new char[temp_count]创建的数组长度是0,后续往temp[temp_count]赋值时必然触发数组越界。由于最多只会缺失26个英文字母,直接将数组初始化为长度26即可。 - 第二个错误:遍历字符数组
c的循环条件错误。Java中String.toCharArray()返回的字符数组末尾不会自动追加\0结束符,你写的c[i]!='\0'会导致循环一直执行到超出数组下标范围,触发越界,要把循环条件改成i < c.length。 - 额外逻辑问题:最后输出缺失字符的原循环条件为
i < temp_count-1,会导致最后一个缺失字符不会被打印,需要调整输出逻辑。
修正后可运行代码
import java.util.Scanner; public class oop2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int temp_count = 0; char[] c = str.toCharArray(); // 初始化数组长度为26,最多缺失26个字母 char[] temp = new char[26]; // 大写转小写 for(int i=0; i<str.length(); i++) { if (Character.isUpperCase(c[i])) { c[i]=(char) (c[i]+32); } } // 检查每个字母是否存在 for(char x = 'a'; x<='z'; x++) { int count=0; // 修正循环条件,避免越界 for(int i=0; i < c.length; i++) { if (c[i]==x) { count++; } } if (count==0) { temp[temp_count]=x; temp_count++; } } // 判断是否为全字母句 if (temp_count==0) { System.out.println("Pangram"); } else { System.out.println("Not Pangram"); System.out.print("Missing Characters: "); // 修正输出逻辑,打印所有缺失字符 for(int i=0; i<temp_count; i++) { if(i != temp_count -1) { System.out.print(temp[i]+", "); } else { System.out.print(temp[i]); } } } sc.close(); } }
内容的提问来源于stack exchange,提问作者WiNT3R
相关产品推荐
相关产品推荐

