java为什么这段代码强制退出?
我已经开始同时学习Java和安卓应用程序开发。目前,我正在尝试使用Log打印一个字符串数组colorsArray。五
<?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 安卓.app.Activity;
import 安卓.os.Bundle;
import 安卓.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--]);
}
}
}
打印使用ForEach()&;printUsingWhile()运行正常,但printReverse方法未运行,应用程序强制在到达之前退出here is the log我正在开发安卓 1.6
请指导本n00b,为什么会发生这种情况
# 1 楼答案
您的代码中有一个错误:
这将导致使用
i = aColors.length
进行循环迭代,这超出了范围您可以在日志中看到: