问题描述
我有以下文件
3
2,3,4,5
6,7,8
9,10
我试图将其转换为传递为双锯齿状数组。 我的意思是,我试图将其存储为
double[][] myArray = {{2,3,4},{6,7},{9}}
double[] secondArray = {5,8,10}
我已经能够从文件中读取值,但我被困在两件事上。
- 如何将值转换为双数组?
- 如何将最后的元素存储到新数组中?
我面临错误,因为我的数组包含逗号分隔值,但我怎样才能将各个值转换为double? 我还是Java的新手,所以我不知道所有内置的方法。
这是我到目前为止所拥有的
public double[] fileParser(String filename) {
File textFile = new File(filename);
String firstLine = null;
String secondLine = null;
String[] secondLineTokens = null;
FileInputStream fstream = null;
try {
fstream = new FileInputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
firstLine = br.readLine(); // reads the first line
List<String> myList = new ArrayList<String>();
while((secondLine = br.readLine()) != null){
myList.add(secondLine);
//secondLineTokens = secondLine.split(",");
}
String[] linesArray = myList.toArray(new String[myList.size()]);
for(int i = 0; i<linesArray.length; i++){
System.out.println("tokens are: " + linesArray[i]);
}
double[] arrDouble = new double[linesArray.length];
for(int i=0; i<linesArray.length; i++)
{
arrDouble[i] = Double.parseDouble(linesArray[i]); #error here
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
1楼
看起来第一行显示文件其余部分的行数。 您可以利用它来预先制作阵列,如下所示:
int n = Integer.parseInt(br.readLine());
double a[][] = new double[n][];
double b[] = new double[n];
for (int i = 0 ; i != n ; i++) {
String[] tok = br.readLine().split(",");
a[i] = new double[tok.length-1];
for (int j = 0 ; j != a[i].length ; j++) {
a[i][j] = Double.parseDouble(tok[j]);
}
b[i] = Double.parseDouble(tok[tok.length-1]);
}
类似地,您可以使用String.split
方法来查找要添加到锯齿状数组的条目数。
这样代码变得更短,因为您可以预先分配所有数组。