数组索引超出范围exception(Java)
这是我的代码:
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)
我不完全确定问题是什么或如何解决它。
for ( i = 0; i < total.length; i++ ); ^-- remove the semi-colon here
使用这个分号,循环循环直到i == total.length
,什么也不做,然后你认为是循环的主体被执行。
for ( i = 0; i < total.length; i++ ); // remove this { if (total[i]!=0) System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]); }
for循环循环直到i=26
(其中26是total.length
)然后执行if
,越过数组的边界。 删除;
在for
循环结束时。
你应该删除它
for (i = 0; i < total.length; i++);
这是非常好的java中数组长度的例子,我在这里给出两个例子
public static int linearSearchArray(){ int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7}; int key = 7; int i = 0; int count = 0; for ( i = 0; i< arrayOFInt.length; i++){ if ( arrayOFInt[i] == key ){ System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] ); count ++; } } System.out.println("this Element found the ("+ count +") number of Times"); return i; }
上面我