我在多维数组中存储值时遇到问题。这个想法的主要概念是,我有一个名为user_decide的数组列表,并将其转换为数组。因此,decision数组看起来像[1,45656,8,97,897],但所有行的元素数量并不相同。然后,我将替换[,]和空格分开,并将每个值单独存储在2D数组中。所以,我用","将其拆分,并尝试将每个值存储在不同的位置。一切似乎都打印得很好,甚至cut[j]也是我想要存储的,但我得到了java.lang.NullPointerException,但我没有得到。count变量实际上是count=user_decide.size()
String [] decide = user_decide.toArray(new String[user_decide.size()]);
for (int i = 0; i < count; i ++){
decide[i] =
decide[i].replaceAll("\s", "").replaceAll("\[","").replaceAll("\]", "");
}
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
String [] cut = decide[i].split("\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
另一个问题是为什么我不能将它存储在Int[][]数组中?有办法做到这一点吗?
非常感谢。
**编辑**
在我接受了这个问题之后,我只是对我的答案做了一个编辑。我正在尝试将它存储在2D int数组中。
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length];
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
String [][] data1 = new String[count][];
for (int i = 0; i < count; i++){
data1[i] = decide[i].split("\,");
System.out.println(Arrays.toString(data1[i]));
}
此外,您不需要转义逗号。
编辑
看到你的编辑了。有一个大错误,请参阅我在您的代码中的评论:
String [][] data1 = new String[user_decide.size()][];
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
data1[i] = decide[i].split("\,");
for (int j = 0; j < data1[i].length; j++) {
data[i] = new int [data1[i].length]; // This line has to be prior to the
// inner loop, or else you'll overwrite everything but the last number.
data[i][j] = Integer.parseInt(data1[i][j]);
System.out.println(data1[i][j]);
}
}
如果你只想要int[]
,我会这么做:
int [][] data = new int [user_decide.size()][];
for (int i = 0; i < user_decide.size(); i++){
String[] temp = decide[i].split(",");
data[i] = new int [temp.length];
for (int j = 0; j < temp.length; j++){
data[i][j] = Integer.parseInt(temp[j]);
System.out.println(data1[i][j]);
}
}
可能有更好的方法,但我不知道为什么在循环中使用user_decide.size()
(集合)作为条件,使用decide[i]
(数组)。我没有充分的理由考虑混合使用,因为这可能会导致错误。
在java中,在复制内容之前,还需要分配data[i]
:
for (int i = 0; i < count; i++){
data1[i] = new String[cut.length];
String [] cut = decide[i].split("\,");
for (int j = 0; j < cut.length; j++){
System.out.println(cut[j]);
data1[i][j] = cut[j];
}
}
复制内容之前: