用java读取和格式化数据
我有一个作业,我必须从文本文件中读取数据。文件中的数据如下所示:
1946-01-01;07:00:00;-1.8;G
1946-01-01;13:00:00;-1.0;G
1946-01-01;18:00:00;-1.9;G
1946-01-02;07:00:00;-1.7;G
我想格式化数据并将其放入适当的数据结构中,这样我就可以搜索两个日期之间所有日期的平均温度。当我的代码是:
package algo.weatherdata;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.List;
/**
* Provides methods to retrieve temperature data from a weather station file.
*/
public class WeatherDataHandler {
/**
* Load weather data from file.
*
* @param filePath path to file with weather data
* @throws IOException if there is a problem while reading the file
*/
public void loadData(String filePath) throws IOException {
//Read all weather data
List<String> fileData = Files.readAllLines(Paths.get(filePath));
/**
* TODO: Format data and put it in appropriate data structure.
*/
}
# 1 楼答案
您可以在行上迭代并用分隔符分隔每行(在您的示例中为
;
):然后,您可以根据自己的喜好使用数组(存储它们,处理它们)
# 2 楼答案
让我们假设以下类将包含天气数据:
接下来,我们将数据文件分析为当前结构,并将它们全部收集到一个列表中:
然后你可以使用一个列表在日期之间搜索并计算平均温度
# 3 楼答案
我在我的工作空间中尝试了上面的Dinar Zaripov代码,添加了生成日期时间、温度和标签的getter方法
for循环后的继续
但我的平均值是**平均值::1.5999999** 然而,根据数学计算,它应该是1.6。有人能告诉我怎么做吗?或者这是正确的
当我给出以下数据时,我得到了正确的平均值:)