【发布时间】:2018-02-19 05:03:48
【问题描述】:
如何从文本文件中读取数据,将每个单词/数字拆分并存储到数组中?
【问题讨论】:
-
Arrays.stream(str.split(" ")).skip(1).mapToDouble(Double::parseDouble).toArray();
如何从文本文件中读取数据,将每个单词/数字拆分并存储到数组中?
【问题讨论】:
Arrays.stream(str.split(" ")).skip(1).mapToDouble(Double::parseDouble).toArray();
您应该将文件中的行读取为字符串,将其拆分并转换为双精度。试试这个:
try {
Scanner scan = new Scanner(new File("path/to/file"));
String str = scan.nextLine();
String[] split = str.split("\\s+");
// remove first element
String[] x = new String[split.length-1];
for (int i = 0; i < x.length; i++) {
x[i] = split[i+1];
}
double[] numbers = new double[x.length];
for (int i = 0; i < x.length; i++) {
numbers[i] = Double.parseDouble(x[i]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
我还添加了一些内容来删除第一个元素,因为它不是double。您可以将两个 for 循环压缩在一起,避免使用单独的 x 数组。这可以按如下方式完成:
String[] split = str.split("\\s+");
// create double array while ignoring the first element
double[] numbers = new double[split.length-1];
for (int i = 0; i < numbers .length; i++) {
numbers[i] = Double.parseDouble(split[i+1]);
}
【讨论】:
String[] x。只需加载正确大小的双精度数组
String[] x = ... 和 for 循环来删除第一个。只需忽略下一个 for 循环中将 string[] 转换为 double[] 的第一个元素。