数组索引越界异常的(JAVA) [英] Array Index Out of Bounds Exception (Java)
问题描述
下面是我的code:
公共类countChar { 公共静态无效的主要(字串[] args){
INT I;
字符串userInput =新的String(); userInput = Input.getString(请输入一句); INT [] =总totalChars(userInput.toLowerCase()); 对于(i = 0; I< total.length;我++);
{
如果(总[I]!= 0){
的System.out.println(家书+(字符)('A'+ I)+数=+总[I]);
}
}
} 公共静态INT [] totalChars(字符串userInput){
INT [] =总INT新[26];
INT I;
对于(i = 0; I< userInput.length();我++){
如果(Character.isLetter(userInput.charAt(ⅰ))){
总[userInput.charAt(ⅰ) - '一'] ++;
}
}
总回报;
}
}
该计划的目的是要求用户输入一个字符串,再算上的时候每个字符的字符串中使用的数量。
当我去编译程序,它工作正常。当我运行该程序,我能请在弹出框中的字符串,但之后,我提交的字符串和preSS OK,我得到一个错误,说
异常线程mainjava.lang.ArrayIndexOutOfBoundsException:26
在countChar.main(countChar.java:14)
我不能完全确定是什么问题或如何解决它。
为(i = 0; I< total.length;我++);
^ - 在这里删除分号
有了这个分号,循环循环,直到我== total.length
,什么都不做,然后你想到的是执行循环体。
Here is my code:
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;
}
}
The program's purpose is to ask the user for a string, and then count the number of times each character is used in the string.
When I go to compile the program, it works fine. When I run the program, I am able to enter a string in the popup box, but after I submit the string and press OK, I get an error, saying
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
at countChar.main(countChar.java:14)
I'm not completely sure what the problem is or how to fix it.
for ( i = 0; i < total.length; i++ );
^-- remove the semi-colon here
With this semi-colon, the loop loops until i == total.length
, doing nothing, and then what you thought was the body of the loop is executed.
这篇关于数组索引越界异常的(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!