Search code examples
javatext-filesreadfile

Find the avg of a set and the class using a text file in java


Marks for a class are stored in a text file called “marks3.txt”. The marks are saved in the following format: The first number represents the total number of (two-digit) marks stored sequentially in each line of text. Each line of text represents a set of marks.

For example (the txt file would contain the following numbers) 4567687509 569563

the marks are:

45%, 67%, 68%, 75%, 9%

56%, 95%, 63%

Write a method that will calculate the average of each set of marks as well as the overall average.

Below is the code I have created, I'm confused on how I would loop through the file until I have the two numbers that would make up the mark. Another thing I'm stuck on is how the method would be called.

import java.io.*;


public class ReadFile {


public static int calcAvg (String x) throws IOException {
    int avg = 0;
    int count = 0;
    
    
    FileReader fr = new FileReader ("/home/sharma6a/marks.txt");
    BufferedReader br = new BufferedReader (fr);
    
    while ((x = br.readLine()) != null) {
        if (count <= 2) {
            
        }
    }
    
    br.close();
    
    return avg;
}

Solution

  • considering an input file like

    45676875
    09569563
    

    first I will have a method to read the file and transform it into a better structure to use.

       public List<Integer> readFile() throws FileNotFoundException {
        List<Integer> numbers = new ArrayList<>();
        String line = "";
        try {
            FileReader fr = new FileReader("src/main/resources/numbers.txt");
            BufferedReader br = new BufferedReader(fr);
    
            while ((line = br.readLine()) != null) {
                for (int i = 0; i <= line.length() - 2; i+=2) {
                    char[] chars = line.toCharArray();
                    int number = Integer.parseInt(String.valueOf(chars[i]) + String.valueOf(chars[i+1]));
                    numbers.add(number);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return numbers;
    }
    

    then I will have the method to calculate the AVG

    public float calcAvg(List<Integer> numbers) throws IOException {
            int sum = 0;
            for (int number: numbers){
                sum+= number;
    
            }
            return sum/(numbers.size());
        }
    

    of course, you need a start method to make things happen

    something like

    public void init() throws IOException {
        List<Integer> numbers = readFile();
        float result = calcAvg(numbers);
        System.out.println(result);
    
    }