3
我有一个read()方法,里面我想要分开字符串(它们之间有空格)并将它们放入一个二维数组中,但在此之前,我摆脱了所有空间。数组初始化后,它被赋予CSV构造函数,并创建它自己的2D数组。 问题是我总是收到以下错误:“csv = new CSV(sr)”中的变量sr可能未被初始化。 如何确保我的数组获取有效的字符串?在java中输入到两个二维数组的CSV输入
private String[][] tomb;
private CSV(String[][] t2) {
tomb = new String[t2.length][];
for(int i = 0; i < t2.length; i++) {
tomb[i] = new String[t2[i].length];
for(int j = 0; j < t2[i].length; j++) {
tomb[i][j] = t2[i][j];
}
}
}
public static CSV read(Scanner sc) {
String[][] sr;
int n = 0;
while (sc.hasNextLine())
{
String line = sc.nextLine();
String[] str = line.split(",");
sr = new String[str.length][];
for (int i = 0; i < str.length; i++) {
sr[i][n].replaceAll("\\s+","");
}
n++;
}
CSV csv = new CSV(sr);
return csv;
}
谢谢!它解决了这个问题,但当然当我想运行它时,NullPointerException出现在sr [i] [n] .replaceAll(“\\ s +”,“”);行。我不能给数组 –
@AkosFajszi一个单一的字符串,你会得到一个空指针异常,因为'sr'为空。你需要在'sr = new String [str.length] [];'之后的'sr'中存储一些东西 – Libby