JAVA中string型数组转int型数组的问题

JAVA中string型数组转int型数组的问题
String s1 = "2013-02-17";
String s2 = "1994-03-19";

String[] str1 = s1.split("-");
String[] str2 = s2.split("-");

int x1[] = new int[]{};
int x2[] = new int[]{};

for (int i = 0; i < 3; i++ ){
x1[i] = Integer.parseInt(str1[i]);
x2[i] = Integer.parseInt(str2[i]);
}
这段程序为什么会报下标越界呢?
这是因为你声明数睁袭组时写成了Int x1[]=new int[]{};这样悉唤兄写就链辩相当于直接把数组声明成长度为0,你可以打印一下看看输出x1.length肯定为0.数组的长度是不可变得,所以你后边写的就下表越界了。你可以声明成int[] x1 = new int[3];int[] x2 = new int[3];这样肯定不会错的。
int x1[] = new int[]{};
int x2[] = new int[]{};
这一段没声明拿改消数组的长度歼迟吧
修消知改成
int x1[3] = new int[]{};
int x2[3] = new int[]{};
试试
String s1 = "2013-02-17";
String s2 = "1994-03-19";

String[] str1 = s1.split("-");
String[] str2 = s2.split("-");

int x1[] = new int[str1.length];
int x2[] = new int[str2.length];

for (int i = 0; i < 3; i++ ){
x1[i] = Integer.parseInt(str1[i]);
x2[i] = Integer.parseInt(str2[i]);
}
数组没长度
← 上一篇: 下一篇: →