Android 2.3.3
这是我的代码......
String[] expression = {""}; //globally declared as empty
somewhere in the code below, I am trying to assign a string to it.
expression[0] = "Hi";
I keep getting the following error...
12-08 22:12:19.063: E/AndroidRuntime(405): java.lang.ArrayIndexOutOfBoundsException
有人可以帮我这个.. 我们可以像我一样直接访问索引0吗?
实际代码:::
static int x = 0; // global declaration
String[] assembledArray = {""}; // global declaration
assembleArray(strSubString, expression.charAt(i)); //Passing string to the method
//Method Implementation
private void assembleArray(String strSubString, char charAt) {
// TODO Auto-generated method stub
assembledArray[x] = strSubString;
assembledArray[x+1] = String.valueOf(charAt);
x = x+2;
}
答案 0 :(得分:1)
问题不在assembledArray[x]
;它在assembledArray[x+1]
。
在第一次迭代时,x+1 = 1
,因此您无法访问该数组的那一部分。我建议使用动态数组,即ArrayList
:
ArrayList<String> assembledArray = new ArrayList<String>(); // global declaration
assembleArray(strSubString, expression.charAt(i)); //Passing string to the method
//Method Implementation
private void assembleArray(String strSubString, char charAt) {
assembledArray.add(strSubString);
assembledArray.add(String.valueOf(charAt));
}
这样,Java负责调整大小,您无需跟踪x
。