gpt4 book ai didi

Java:数组索引越界异常2

转载 作者:行者123 更新时间:2023-12-01 08:01:31 25 4
gpt4 key购买 nike

我正在编写一个简单的 Java 程序,要求用户输入一个字符串,然后计算并显示字母表中每个字母在该字符串中出现的次数。当我编译时,出现此错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -25
at StringLetters.countLetters(StringLetters.java:43)
at StringLetters.main(StringLetters.java:23)

我已经研究了与我类似的问题的其他解决方案,但没有一个有帮助。有人有什么想法吗?谢谢。

    import java.util.Scanner;

public class StringLetters
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string of words.");
String s = scan.nextLine();

int[] counts = countLetters(s.toUpperCase());

for(int i = 0; i < counts.length; i++)
{
if (counts[i] != 0)
{
System.out.println((char)('a' + i) + " appears " + counts[i] + ((counts[i] == 1) ? "time" : " times"));
}
}
}


public static int[] countLetters(String s)
{
int[] counts = new int[26];

for (int i = 0; i < s.length(); i++)
{
if(Character.isLetter(s.charAt(i)))
{
counts[s.charAt(i) - 'a']++;
}
}

return counts;
}

}

最佳答案

在传递给计数方法的参数 String 中,有一些字母不是小写英文字母,这会破坏您的代码。

事实上,它们都不是小写,因为您正在调用 s.toUpperCase() 并且您似乎打算调用 s.toLowerCase()。此外,您还需要过滤掉标点符号和任何非字母字符。您已经在此处执行此操作:if (Character.isLetter(s.charAt(i)))

所以只需将 s.toUpperCase() 更改为 s.toLowerCase() 就可以了。

关于Java:数组索引越界异常2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985762/

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