CSV 文件和操作

csv file and manipulation

提问人:Allen Hay 提问时间:5/8/2021 最后编辑:Allen Hay 更新时间:5/8/2021 访问量:75

问:

S.M.Tido,112,145,124
P.julio,178,145,133
Carey,92,100,123
Elain,87,92,92
Theodore,178,155,167

我已经阅读了上面的文本文件,并试图找到每行中 3 个读数的平均值。但是我只能找到单列的平均值,因为我的 for 循环逻辑不起作用。谁能告诉我如何找到每行的平均值?

   import java.util.Scanner;
   import java.io.*;
    
    public class PatientDetails{
    
        public static void main(String[] args){
        
            String fileName = "patient.txt";
            File file = new File(fileName);
            
            try{
                Scanner inputStream = new Scanner(file);
                int sum = 0;
                int noOfReadings = 3;
                
                while(inputStream.hasNext()){
                    String data = inputStream.next();
                    
                    
                    String[] values = data.split(",");
                    int readings1 = Integer.parseInt(values[1]);
                    int readings2 = Integer.parseInt(values[2]);
                    int readings3 = Integer.parseInt(values[3]);
                    
                    
                    sum = readings1 + readings2 + readings3;
                    }   
                    
                inputStream.close();
                System.out.println("Average = "+sum/noOfReadings);
            }
            catch(FileNotFoundException e){
                e.printStackTrace();
            }
        }
    
    }

注意:

Note : I have not learnt data structures in Java so I cannot use lists
In my code.
Java CSV for 循环 IO 平均

评论


答:

0赞 M. Dudek 5/8/2021 #1

只需将您移动到循环中,然后将 back 更改为 .println()sum0

Scanner inputStream = new Scanner(file);
int sum = 0;
int noOfReadings = 3;

while (inputStream.hasNext()) {
    String data = inputStream.next();

    String[] values = data.split(",");
    int readings1 = Integer.parseInt(values[1]);
    int readings2 = Integer.parseInt(values[2]);
    int readings3 = Integer.parseInt(values[3]);

    sum = readings1 + readings2 + readings3;
    System.out.println("Average = " + sum / noOfReadings);
    sum = 0;
}

inputStream.close();