2014-04-06 233 views
0

我在我的第一類Java編程中,我們給出的一個賦值是創建一個值字符串,它以相反的順序顯示逗號。我知道我可能錯過了一些非常簡單的事情,但經過幾個小時的努力,我只是不知道自己的錯在哪裏?錯誤消息:線程「main」中的異常java.lang.ArrayIndexOutOfBoundsException:-1

我的代碼工作,但我不斷收到此錯誤信息:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 
    at ip2_jolley.IP2_Jolley.main(IP2_Jolley.java:148) 
Three, Two, One Java Result: 1 

這是我使用的代碼:

String[] f = {"One", "Two", "Three"}; 
if (f.length > 0) System.out.print (f[2]); 
for (int i = 1; i < f.length; i--){ 
    System.out.print(", " + f[i]); 
} 
+0

它不會讓我點擊向上箭頭,所以我編輯,以感謝他們。 – Violette

+0

..當時我也不允許發表評論。 – Violette

回答

1

您與INT I = 1開始你的循環,然後通過1減少它的每一個循環,這將導致i是低於0

而不是使用int i = 1,你可能想使用int i = f.length

編輯

你想要的大概是這樣的:

String[] f = {"One", "Two", "Three","Four","Five"}; 

    //start at f.length - 1, continue until there is no item left 
    for (int i = f.length-1; i >= 0; i--){ 

     //print current item 
     System.out.print(f[i]); 

     //if it is not the last item, print separator 
     if(i>0){ 
      System.out.print(", "); 
     } 
    } 
} 

一些解釋

+1

謝謝你完美的工作! – Violette

0

你的意思是:

for (int i = 0; i < f.length; i++) 

取代:

for (int i = 1; i < f.length; i--) 
+0

@Downvoters。請給出意見。 – user3504561

+2

我沒有downvote答案,但我想這是因爲OP特別是試圖以相反的順序顯示值。 –

+0

好的,我會刪除我的答案。 – user3504561

2

在您的代碼編輯,你從1開始,循環,直到數組的長度,但每次遞減我。這有點混雜起來。你想要做的是從你的數組的末尾開始(如f.length - 1),並繼續移動到數組的「左邊」,直到它開始爲止。所以你想這個:

for (int i = f.length-1; i >= 0; i--){ 
    System.out.print(f[i]); 
} 
+0

這會很好,如果你解釋*爲什麼* – rpax

+0

@rpax:現在好點? –

+0

是的。您值得我的+1 – rpax

相關問題