0

安卓 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;

    }
4

1 回答 1

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.

于 2012-12-08T17:00:47.557 回答