Question

I have a txtfile called "averages" that looks like:

1 4 5 3 -1
2 8 9 3 2 -1
4 8 15 16 23 42 -1
3 -1

I want to be able to read in each line and calculate the average of each line whenever a "-1" is reached. I have written the code to read in the file and print it to the command line, I'm just having trouble finding the averages of each line. Any help would be greatly appreciated. Thanks!

import java.io.*;
import java.util.*;

public class Test {

    public static void main(String[] args) {
        BufferedReader reader = null;

        try {
            String currentLine;

            reader = new BufferedReader(new FileReader("averages.txt"));
            while  ((currentLine = reader.readLine()) != null) {
                System.out.println(currentLine);
            }
        } catch (IOException err) {
            err.printStackTrace();
        } finally {
            try {
                if (reader != null)reader.close();
            } catch (IOException err) {
                err.printStackTrace();
            }
        }

}
}
Was it helpful?

Solution

You could do it by doing the following:

  • split the currentLine using split method:

    String[] nums = currnetLine.split("\\s+");
    
  • loop over the nums and parse each elements to int then add it to a sum variable

    int sum = 0;
    for (int i = 0; i < nums.length; i++) {
        int num = Integer.parseInt(nums[i]);
        if(num != -1) {
            sum += num;
        }
    }
    
  • Finally calculate the average.

    sum/(nums.length - 1);// -1 because you need to execlude the -1 at the end of your line
    

OTHER TIPS

I'd try something like this:

int sum = 0;

String[] values = currentLine.split(" ");

for (String value : values) {
    int n = Integer.parseInt(value);

    if (n < 0) {
        break;
    }

    sum += n;
}

int count = values.length - 1;
// calculate average from sum and count

In Java 7+, the Scanner object is available and has a variety of useful functions to use.

1.) First read in the line Scanner scanner = new Scanner("1 51 2 52");

2.) From your code above, if you have a space delimiter, it is easy to work with scanner.useDelimiter(" ");

3.) If scanner.hasNext() then scanner.next() for the next string.

Iterate the list using Integer.parseInt("1") to get the value, sum, then average.

Please try this:

import java.io.*;
import java.util.*;

public class Test {

    public static void main(String[] args) {
        BufferedReader reader = null;
        try {
            String currentLine;
            reader = new BufferedReader(new FileReader("averages.txt"));
            while  ((currentLine = reader.readLine()) != null) {
                System.out.println(currentLine);
                StringTokenizer st=new StringTokenizer(currentLine," ");
                int count=st.countTokens();
                int array[]=new int[count-1];
                int i=0;
            while(st.hasMoreTokens()&&i!=count-1)
             {
                array[i]=Integer.valueOf(st.nextToken());
                i=i+1;
             }
        int sum=0;
            for(int x=0;x<array.length;x++)
                {
                    sum=sum+array[x];
                }
        float average=(float)sum/array.length;
        System.out.println("The average of this line is: "+average);
            }
        } catch (IOException err) {
            err.printStackTrace();
        } finally {
            try {
                if (reader != null)reader.close();
            } catch (IOException err) {
                err.printStackTrace();
            }
        }
}
}

My logic is that you read a line at a time and separate them by spaces. Then you convert those separated string into Integer. Last step is add them up and do some math to get the average.

Hope this helps. Thanks!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top