如何从文本文件中读取数据,将每个单词/数字拆分并存储到数组中?
答案 0 :(得分:1)
您应该从文件中读取该行的字符串,将其拆分并转换为double。试试这个:
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]);
}