如何访问第一列数据并分配给Java数组中的另一个变量?

问题描述 投票:0回答:2

我有一个.txt文件,带有一些值(附加)。我需要对每个列数据执行平均和求和运算。读取文件后,我无法访问列数据。Data file

public class EEG {

    public static void main(String[] args)  {
        String pathToCsv = "C:\\Users\\Raghu\\Desktop\\EEG files\\testEEGData.txt"; 
        List<String> l2 = new ArrayList<>();
         l = readFileInList(pathToCsv);     

        for(int i = 0; i < 1; i++) 
              System.out.println(l.get(i));
            // I want to performe operation here, like sum and average of first column


    public static List<String> readFileInList(String fileName) 
      {       
        List<String> lines = Collections.emptyList(); 
        try
        { 
          lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8); 
        } 

        catch (IOException e) 
        { 
          e.printStackTrace(); 
        } 
        return lines; 
      } 
java arrays list readfile
2个回答
0
投票

显示文本文件。那我可以帮你。

示例:

public class App { 

/*
    data.txt:
    5
    7
    8
    10
*/
public static void main(String[] args) {
    App app = new App();
    app.calculation();
}

private void calculation() {
    String fileName = "./data.txt";

    try {
        List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
        double sum = 0;
        double avg = 0.0;
        int count = 0;

        for (String line : lines) {
            if (line.matches("-?\\d+(\\.\\d+)?")) {
                sum += Double.parseDouble(line);      
                count++;
            }
        }

        avg = sum/count;

        System.out.println("sum = " + sum);  // 30.0
        System.out.println("avg = " + avg);  // 7.5
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}


0
投票

用逗号分割字符串并将第一个元素视为数字

double value = Double.parseDouble(l.get(i).split(",")[0]);

映射列表:

List<Double> numbers = l.stream()
      .map(line -> Double.parseDouble(line.split(",")[0]))
      .collect(Collectors.toList());

并且可以计算总和:

numbers.stream().reduce(Double::sum)

放在一起:

List<String> l = readFileInList(pathToCsv); 

List<Double> numbers = l.stream()
      .map(line -> Double.parseDouble(line.split(",")[0]))
      .collect(Collectors.toList());

Double sum = numbers.stream().reduce(Double::sum).get();

Double avg = sum / numbers.size();
© www.soinside.com 2019 - 2024. All rights reserved.