我有一个 read() 方法,在里面我想分离字符串(它们之间有空格)并将它们放在一个二维数组中,但在此之前我去掉了所有空格。数组初始化后,它被提供给 CSV 构造函数,它正在创建自己的二维数组。 问题是我总是收到以下错误:CSV csv = new CSV(sr) 时“变量 sr 可能尚未初始化”。 我如何确保我的数组获得有效的字符串?
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;
}
最佳答案
可以通过在初始化中将sr
设置为null
来解决这个错误:
String[][] sr = null;
如果您想确保 sr
设置正确,您可以在 while 循环完成后检查 sr
是否仍然是 null
。
关于java - CSV输入到java中的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40005782/