[英]Reading txt file data into doubles
我正在嘗試將文本文件中的數據保存到包含雙精度數的數組中。 我已經讓它適用於整數,但我想添加非 integer 數據,到目前為止我還想不通。 到目前為止,這是我的代碼:
公共 class 主類 {
public static void main(String[] args) throws FileNotFoundException {
List<Double> E0 = Arrays.asList();
List<Double> E1 = Arrays.asList();
List<Double> E2 = Arrays.asList();
List<Double> C = Arrays.asList();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("C:\\Data.txt"));
String line = reader.readLine();
while (line != null) {
Double lineParts = line.split(",");
E0.add(lineParts[0]);
E1.add(lineParts[1]);
E2.add(lineParts[2]);
C.add(lineParts[3]);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(E0);
System.out.println(E1);
System.out.println(E2);
System.out.println(C);
}
}
這是我的數據:
1,1,4,-1
1,2,9,1
1,5,6,1
1,4,5,1
1,6,7,-1
1,1,1,-1
下面的代碼顯示了如何解析一行並將條目轉換為雙精度。
import java.util.Arrays;
public class ParseDouble {
public static void main(String[] args) {
String line = "1,2,3,-4";
String[] lineSplit = line.split(",");
double[] values = new double[lineSplit.length];
for (int i = 0; i < lineSplit.length; i++) {
values[i] = Double.parseDouble(lineSplit[i]);
}
System.out.println(Arrays.toString(values)); // [1.0, 2.0, 3.0, -4.0]
}
}
使用您的代碼,以下幾行應該可以完成工作:
public class MainClass {
public static void main(String[] args) throws FileNotFoundException {
List<Double> E0 = new ArrayList();
List<Double> E1 = new ArrayList();
List<Double> E2 = new ArrayList();
List<Double> C = new ArrayList();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("C:\\Data.txt"));
String line = reader.readLine();
while (line != null) {
String[] lineParts = line.split(",");
E0.add(Double.parseDouble(lineParts[0]));
E1.add(Double.parseDouble(lineParts[1]));
E2.add(Double.parseDouble(lineParts[2]));
C.add(Double.parseDouble(lineParts[3]));
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(Arrays.toString(E0.toArray()));
System.out.println(Arrays.toString(E1.toArray()));
System.out.println(Arrays.toString(E2.toArray()));
System.out.println(Arrays.toString(C.toArray()));
}
}
您的問題的完整答案是將 static 分離方法轉換為完全動態解析方法,沒有任何錯誤,這個答案是最安全的解決方案,不取決於您插入的數據的長度。
您可以借助包含雙精度值列表的列表來實現此目的
使用您的數據采樣:
List<List<Double>> lines = new ArrayList<>();
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("C:\\Data.txt"));
String line = reader.readLine();
while (line != null) {
List<Double> lineList = new ArrayList<>();
String[] lineParts = line.split(",");
for (String linePart : lineParts) {
lineList.add(Double.valueOf(linePart));
}
lines.add(lineList);
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(lines);
}
問候:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.