这是我的代码:
public class countChar {
public static void main(String[] args) {
int i;
String userInput = new String();
userInput = Input.getString("Please enter a sentence");
int[] total = totalChars(userInput.toLowerCase());
for (i = 0; i < total.length; i++);
{
if (total[i] != 0) {
System.out.println("Letter" + (char) ('a' + i) + " count =" + total[i]);
}
}
}
public static int[] totalChars(String userInput) {
int[] total = new int[26];
int i;
for (i = 0; i < userInput.length(); i++) {
if (Character.isLetter(userInput.charAt(i))) {
total[userInput.charAt(i) - 'a']++;
}
}
return total;
}
}
程序的目的是向用户询问字符串,然后计算字符串中每个字符的使用次数.
当我去编译程序时,它工作正常.当我运行程序时,我能够在弹出框中输入一个字符串,但在我提交字符串并按OK后,我收到错误,说
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at countChar.main(countChar.java:14)
我不完全确定问题是什么或如何解决它.