[英]Array Index Out of Bounds 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
循環結束時。
這是非常好的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;
}
上面我<arrayOFInt.length; 不需要減去一個數組的長度; 但如果你我<= arrayOFInt.length -1; 是必要的其他明智的arrayOutOfIndexException發生,希望這會對你有所幫助。
你應該刪除它
for (i = 0; i < total.length; i++);
import java.io.*;
import java.util.Scanner;
class ar1 {
public static void main(String[] args) {
//Scanner sc=new Scanner(System.in);
int[] a={10,20,30,40,12,32};
int bi=0,sm=0;
//bi=sc.nextInt();
//sm=sc.nextInt();
for(int i=0;i<=a.length-1;i++) {
if(a[i]>a[i+1])
bi=a[i];
if(a[i]<a[i+1])
sm=a[i];
}
System.out.println("big"+bi+"small"+sm);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.