Search code examples
javacounttext-filesaveragebufferedreader

Average of stacked integers from a txt file using BufferedReader class and Integer.parseInt


I'm supposed to somehow get the average of the stacked integers in the text file. I'm new to this and even getting them to print was difficult for me. I have to use something like this number = Integer.parseInt(readLine); there somewhere but I just don't know how. If anyone could give some hint of what to do I would be most thankful.

The text file has just a dozen integers stacked as in one number on one line. Nothing else. Here's my code so far:

import java.io.*;

public class GradesInFile {

        public static void main(String[] args) throws IOException {
            String fileName = "grades.txt";
            String readRow = null;
            boolean rowsLeft = true;
            BufferedReader reader = null;
            FileReader file = null;

            file = new FileReader(fileName);

            reader = new BufferedReader(file);

            System.out.println("Grades: ");


            while (rowsLeft) {
                readRow = reader.readLine();

                if (readRow == null) {
                    rowsLeft = false;


                } else {
                    System.out.println(readRow);

                }
            }


            System.out.println("Average: ");
            reader.close();
        }
    }

Solution

  • You are almost there just think how to keep track of the values you have so once you get out of the while loop you can return the average. (Hint Hint keep a list of the numbers)

    So:

    while (rowsLeft) {
        readRow = reader.readLine();
        if (readRow == null) {
           rowsLeft = false;
        } else {
           //Convert the String into a Number (int or float depending your input)
           //Saving it on a list.
           System.out.println(readRow);
        }
    }
    
    
    //Now iterate over the list adding all your numbers
    //Divide by the size of your list
    //Voila
    System.out.println("Average: ");
    reader.close();