如何从文本文件中读取数据,拆分每个单词/数字并将其存储到数组中?
最佳答案
您应该从文件中将 的行作为字符串读取,将其拆分并转换为 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]);
}
关于JAVA如何按空格分割并存储到双数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48859793/