2014-09-23 33 views
1

警告:我對Java和編程一般都很陌生。我會盡量做到儘可能清楚。爲什麼我的int []數組循環出界?

我試圖採取一個簡單的整數(inputnumber),將其轉換爲字符串(temp),創建通過這個INT []數組新的int []數組(numberarray),以及循環,從去年開始數字,並打印出數字的名稱。

由於Eclipse調試,我確信從整數到字符串轉換爲int []數組是功能正常的,但難以理解爲什麼我從Eclipse獲得ArrayOutOfBounds消息來處理如此簡單的for循環。對於我做錯什麼的任何線索表示讚賞。我越來越

String temp = inputnumber.toString(); 
    int[] numberarray = new int[temp.length()]; 

    for (int i=0;i<temp.length();i++) { 
     numberarray[i] = temp.charAt(i); 
    } 


    for (int i=temp.length();i>0;i--) { 

     if (numberarray[i]==1) System.out.print("one."); 
     if (numberarray[i]==2) System.out.print("two."); 
     if (numberarray[i]==3) System.out.print("three."); 
     if (numberarray[i]==4) System.out.print("four."); 
     if (numberarray[i]==5) System.out.print("five."); 
     if (numberarray[i]==6) System.out.print("six."); 
     if (numberarray[i]==7) System.out.print("seven."); 
     if (numberarray[i]==8) System.out.print("eight."); 
     if (numberarray[i]==9) System.out.print("nine."); 
     if (numberarray[i]==0) System.out.print("zero"); 
    } 

Eclipse的錯誤信息是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
at jt.Intermediate8.main(Intermediate8.java:44) 

回答

7

數組在Java中是0索引的。這意味着最後一個值是在指數NUMBER_OF_ELEMENTS - 1

因此,在你的for循環,你應該改變

int i=temp.length()  // this is last index + 1 (since we are starting from 0) 

要:

int i=temp.length() - 1 // this is last index 

此外,作爲@ brso05說,不要忘記改變你的循環結束條件爲i>=0,因爲上一次倒退的值將在索引0處。

for循環:

for (int i = temp.length(); i >= 0; i--) 
+0

感謝您幫助我的極端明顯。 +1。 – LanceLafontaine 2014-09-23 17:08:55

+0

如果你想擊中所有元素,請確保i> = 0而不是i> 0,否則你會跳過第一個元素(請參閱我的文章)。 – brso05 2014-09-23 17:13:04

3

你開始在temp.length循環()。這不是一個有效的索引。也許你想temp.length() - 1?

2

你應該做temp.length() - 1,原因是數組索引爲0而不是1所以在陣列中的最後一個元素存儲在開始長度 - 1.如果有10個元素,則0-9是您的索引。如果你想擊中所有元素,也可以將i> 0更改爲i> = 0。

for (int i=(temp.length() - 1);i>=0;i--) {