Why this code Force Quits?
I have starting learning Java and android application development side-by-side. Currently, I a String-array colorsArray which I am trying to print using 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>
Now I am trying to print that array in different ways, just for practice.
package com.gaurish.challenge;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class defaultActivity extends Acti开发者_Python百科vity {
/** 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() run just fine but printReverse method just not run, the application force quits before reaching. here is the log I am building against android 1.6
Please guide this n00b, why this is happening
You have a bug in your code:
while(i<=aColors.length) { ... }
This will cause a loop iteration with i = aColors.length
, which is out of bounds.
You can see this in your log:
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)
精彩评论