Search code examples
javacsvfor-loopioaverage

csv file and manipulation


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

I have read above text file, and tried to find the average values of the 3 readings in every row. But I can only find the average of a single column,because my for loop logic did not work. Can anyone show me how to find the average of every row ?

   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:

Note : I have not learnt data structures in Java so I cannot use lists
In my code.

Solution

  • Just move you println() into the loop, and after that, change the sum back to 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();