有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用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.
         */


    }

共 (3) 个答案

  1. # 1 楼答案

    您可以在行上迭代并用分隔符分隔每行(在您的示例中为;):

    public void loadData(String filePath) throws IOException {
        List<String> fileData = Files.readAllLines(Paths.get(filePath));
    
        String[] lineValues = str.split(";");
        // line values are stored in this array
    }
    

    然后,您可以根据自己的喜好使用数组(存储它们,处理它们)

  2. # 2 楼答案

    让我们假设以下类将包含天气数据:

    public class WeatherData {
    
        private LocalDateTime dateTime;
        private double temperature;
        private String tag;            // I don't really know what is 'G' mean
    
        public WeatherData(LocalDateTime dateTime, double temperature, String tag) {
            this.dateTime = dateTime;
            this.temperature = temperature;
            this.tag = tag;
        }
    }
    

    接下来,我们将数据文件分析为当前结构,并将它们全部收集到一个列表中:

    private List<WeatherData> weatherData = new ArrayList<>();
    
    public void loadData(String filePath) throws IOException {
        List<String> fileData = Files.readAllLines(Paths.get(filePath));
        for(String str : fileData) {
            List<String> parsed = parseData(str);
            LocalDateTime dateTime = LocalDateTime.of(dateOf(parsed.get(0)), 
                                                      timeOf(parsed.get(1)));
            double temperature = Double.parseDouble(parsed.get(2));
            String tag = parsed.get(3);
    
            WeatherData weather = new WeatherData(dateTime, temperature, tag);
            weatherData.add(weather);
        }
    
    }
    
    private List<String> parseData(String s) {
        return Arrays.asList(s.split(";"));
    }
    
    private LocalDate dateOf(String date) {
        return LocalDate.parse(date);
    }
    
    private LocalTime timeOf(String time) {
        return LocalTime.parse(time);
    }
    

    然后你可以使用一个列表在日期之间搜索并计算平均温度

  3. # 3 楼答案

    我在我的工作空间中尝试了上面的Dinar Zaripov代码,添加了生成日期时间、温度和标签的getter方法

    for循环后的继续

    private static float averageTemperature(List<WeaterData> weatherData) 
    {
    
            float sum = 0; // Variable to store the sum
            float count = 0; // Variable to keep the count
    
            if (weatherList != null) {
                for (WeaterData averageWeather : weatherData) {
                    float value = averageWeather.getTemperature();
                    System.out.println(value);
                    if (value <= 0) { // Check if the number is negative
                        sum += value; // Add the value to the current sum
                        count++; // Increment the count by 1
                    }
                }
    
            }
            return (count > 0) ? (sum /count) : 0; // Calculate the average if there were any negative numbers
        }
    

    但我的平均值是**平均值::1.5999999** 然而,根据数学计算,它应该是1.6。有人能告诉我怎么做吗?或者这是正确的

    当我给出以下数据时,我得到了正确的平均值:)

    1946-01-01;07:00:00;-1.8;A
    ** 1946-01-01;13:00:00;-1.1; B**
    1946-01-01;18:00:00;-1.9;C
    1946-01-02;07:00:00;-1.7;D