[英]Parsing text file to jagged array
我有以下文件
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();
}
看起來第一行顯示文件其余部分的行數。 您可以利用它來預先制作陣列,如下所示:
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
方法來查找要添加到鋸齒狀數組的條目數。 這樣代碼變得更短,因為您可以預先分配所有數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.