2011-02-13 38 views
0

我已經開始學習Java和Android應用程序開發並行。目前,我一個String數組colorsArray而我試圖用Log.v爲什麼這段代碼強制退出?

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string name="hello">Hello World, defaultActivity!</string> 
    <string name="app_name">Challenge</string> 
    <string name="red">Red</string> 
    <string name="orange">Orange</string> 
    <string name="yellow">Yellow</string> 
    <string name="green">Green</string> 
    <string name="blue">Blue</string> 
    <string name="indigo">Indigo</string> 
    <string name="violet">Violet</string> 
    <string-array name="colorsArray"> 
     <item>@string/red</item> 
     <item>@string/orange</item> 
     <item>@string/yellow</item> 
     <item>@string/green</item> 
     <item>@string/blue</item> 
     <item>@string/indigo</item> 
     <item>@string/violet</item> 
    </string-array> 
</resources> 

現在我想打印在不同的方式,陣列打印,只是做法。

package com.gaurish.challenge; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 

public class defaultActivity extends Activity { 
    /** Called when the activity is first created. */ 
    public static final String DEBUG_TAG = "PracticeApp"; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    String aColors[] = getResources().getStringArray(R.array.colorsArray); 
    printUsingForEach(aColors); 
    printUsingWhile(aColors); 
    printReverse(aColors); 
} 

private void printUsingForEach(String[] aColors) { 
    for(String i : aColors) { 
     Log.v(DEBUG_TAG, "String array printed using for each loop: " + i); 
    } 
} 

private void printUsingWhile(String[] aColors) { 
    byte i=0; 
    while(i<=aColors.length) { 
     Log.v(DEBUG_TAG, "String array printed using While loop: " + aColors[i++]); 
    } 
} 

private void printReverse(String[] aColors) { 
    int i=aColors.length -1; 
    while(i> (-1)) { 
     Log.v(DEBUG_TAG, "String array printed in reverse order -> " + aColors[i--]); 
    } 
} 
} 

printUsingForEach()& printUsingWhile()運行得很好,但printReverse方法只是不能運行,應用力達之前退出。 here is the log我建立針對Android 1.6的

請指導本的n00b,爲什麼發生這種情況

+0

java.lang.ArrayIndexOutOfBoundsException閱讀日誌正確,這是一個簡單的錯誤看到一個檢查哪一行的錯誤是特別。 defaultActivity.java Line:31 – Blundell 2011-02-13 15:54:53

+0

對不起,我保證會在下次仔細閱讀日誌。謝謝! – CuriousMind 2011-02-13 16:09:56

回答

4

你在你的代碼中的錯誤:

while(i<=aColors.length) { ... } 

這將導致一個循環迭代與i = aColors.length,這是越界。

您可以在日誌中看到這一點:

02-13 15:24:24.226: ERROR/AndroidRuntime(396): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gaurish.challenge/com.gaurish.challenge.defaultActivity}: java.lang.ArrayIndexOutOfBoundsException 
02-13 15:24:24.226: ERROR/AndroidRuntime(396): Caused by: java.lang.ArrayIndexOutOfBoundsException 
02-13 15:24:24.226: ERROR/AndroidRuntime(396):  at com.gaurish.challenge.defaultActivity.printUsingWhile(defaultActivity.java:31)