有 Java 编程相关的问题?

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

JavaCSV文件及其操作

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.

共 (1) 个答案

  1. # 1 楼答案

    只需将println()移动到循环中,然后将sum更改回0

    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();