gpt4 book ai didi

java将文件的输出存储到数组中

转载 作者:行者123 更新时间:2023-12-01 06:17:29 25 4
gpt4 key购买 nike

我有一个关于如何将文件的输出存储到数组中的问题。就我而言,我试图将文件中的所有日期存储到数组中。对于我这样做的方式,编译器提示“不是声明”。我怎样才能解决这个问题?任何帮助将不胜感激。下面是我的代码(错误行前面有反斜杠):

double token[] = new double[9];

File filename = new File("/Users/timothylee/gravity1.txt");

Scanner inFile = new Scanner(filename);

while(inFile.hasNext()){
//////////////// token[] = inFile.nextDouble();
System.out.println(token);
}
inFile.close();

如果需要,这里是文件:

gravity1.txt:
3.70
8.87
9.79
3.70
24.78
10.44
8.86
11.13
0.61

最佳答案

        ArrayList<Double> token = new ArrayList<Double>();

File filename = new File("/Users/timothylee/gravity1.txt");

Scanner inFile = new Scanner(filename);

while(inFile.hasNext()){
token.add(inFile.nextDouble());
}
inFile.close();
System.out.println(Arrays.toString(token));

只需使用 ArrayList,不要让你的生活变得更困难。 ;) 这也使得它更加灵活,因为文件中有多少数据/行并不重要。

关于java将文件的输出存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20549272/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com