通过EditText中的值填充二维数组

时间:2016-05-13 20:45:24

标签: java android arrays android-edittext

我有EditText和数组。我希望通过EditText字段中的值填充数组。 所有字符都是数字。我怎样才能做到这一点? 我试过这个:

...
int [][] a = new int [100][100];
n=1;//now 1, but this value entered in EditText
...
                    if (edit_1.getText().length() > 0) {
                        for (int ii = 0; ii < a.length; ii++) {
                            a[ii][n+1] = Integer.parseInt(String.valueOf(edit_1.getText().charAt(ii)));
                        }
                    }
...
a[1][n+2]=a[1][n+1];
...

我在LogCat中获得了什么:

05-13 23:40:55.046: E/AndroidRuntime(27281): FATAL EXCEPTION: main
05-13 23:40:55.046: E/AndroidRuntime(27281): Process: aectann.dcsmp, PID: 27281
05-13 23:40:55.046: E/AndroidRuntime(27281): java.lang.IndexOutOfBoundsException: charAt: 4 >= length 4
05-13 23:40:55.046: E/AndroidRuntime(27281):    at android.text.SpannableStringBuilder.charAt(SpannableStringBuilder.java:121)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at aectann.dcsmp.Zhegalkin_polynomial.zheg(Zhegalkin_polynomial.java:230)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at aectann.dcsmp.Zhegalkin_polynomial$1.onClick(Zhegalkin_polynomial.java:122)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at android.view.View.performClick(View.java:4811)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at android.view.View$PerformClick.run(View.java:20136)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at android.os.Handler.handleCallback(Handler.java:815)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at android.os.Handler.dispatchMessage(Handler.java:104)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at android.os.Looper.loop(Looper.java:194)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at android.app.ActivityThread.main(ActivityThread.java:5549)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at java.lang.reflect.Method.invoke(Native Method)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at java.lang.reflect.Method.invoke(Method.java:372)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
05-13 23:40:55.046: E/AndroidRuntime(27281):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)

121 - 函数调用;

230 - a[ii][n+1] = Integer.parseInt(String.valueOf(edit_1.getText().charAt(ii)));

1 个答案:

答案 0 :(得分:1)

也许这可能是该例外的解决方案:

if (edit_1.getText().length() > 0) {
    for (int ii = 0; ii < edit_1.getText().length(); ii++) {
            a[ii][n + 1] = Integer.parseInt(String.valueOf(edit_1.getText().charAt(ii)));
        }
}

如果你想只创建这些字符所需的空间,也许你需要使用这样的东西(但我认为这需要改变你访问数据的方式):

int [][] a = new int [100][];
n=1;//now 1, but this value entered in EditText
...     
        if (edit_1.getText().length() > 0) {
            a[n+1] = new int[edit_1.getText().length()];
            for (int ii = 0; ii < a.length; ii++) {
                a[n+1][ii] = Integer.parseInt(String.valueOf(edit_1.getText().charAt(ii)));
            }
        }

希望有所帮助