Java - How to detect the number of lines in the text file and do calculations

Viewed 711

I have a file called SalesData.txt containing the dollar amount of sales that a retail store made each day for a number of weeks. Each line in the file contains seven numbers, which are the daily sales for one week. The numbers are separated by a comma. The following is an example from the file:

1245.67,1490.07,1679.87,2371.46,1783.92,1461.99,2059.77
2541.36,2965.88,1965.32,1845.23,7021.11,9652.74,1469.36
2513.45,1963.22,1568.35,1966.35,1893.25,1025.36,1128.36

I have converted the String to Double and am trying to calculate:

  • The total sales for each week
  • The average daily sales for each week
  • The total sales for all the weeks
  • The average weekly sales

My question is how can Java detect the first line as week 1, the second line as week 2 etc. And calculate the amount. Below is the syntax:

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

public class Q1
{
    public static void main (String [] args) throws IOException,  NumberFormatException
    {
        //Open the text file
        File file = new File("SalesData.txt");
        Scanner inputFile = new Scanner (file);

        //Read the text file
        while (inputFile.hasNext())
        {
            String weekly_Sale = inputFile.nextLine();
            String value = weekly_Sale;

            //Split the text by ","
            StringTokenizer strtk = new StringTokenizer(value, ",");

            //Define array list
            ArrayList<String> numList = new ArrayList<String> ();
            while (strtk.hasMoreTokens ())
            {
                numList.add(strtk.nextToken());
            }

            //Change the data type from String to Double
            for (String item:numList)
            {
                Double result = Double.parseDouble(item);
                //System.out.println(result);
            }
            weekly(result);

        }
        //Close the text file
        inputFile.close();
    }
    // not sure how to detect the week number
    public static void weekly(String numList)
    {
        for (int i=0; i<numList.size; i++)
        {

            System.out.println(numList.get(i));
        }
    }
}
4 Answers

It sounds like a list of lists, where the inner list represents the sales for a particular week, and the outer list represents all of the weeks:

List<List<Double>> saleWeeks;

When parsing the file, each line represents a week so add a new list:

List<Double> salesForTheWeek = new ArrayList<>();
saleWeeks.add(salesForTheWeek);
// parse the line of the file and add the values to salesForTheWeek

Later, each week is related to the index:

List<Double> week1Sales = saleWeeks.get(0);

Then you can iterate (or stream) to add, average, etc.

Create a class WeeklySales which will encapsulate properties for:

The total sales for each week The average daily sales for each week

For each row calculate "The total sales for each week" and " The average daily sales for each week" and populate in list of WeeklySales class.

Use list of WeeklySales class to calculate below:

The total sales for all the weeks The average weekly sales

Create another class to hold above two properties and list of objects and use it.

In a single iteration also a model containing required properties can be populated.

I will give you the part of reading the values, as this is the part you simply "have to know how to do". You'll have to do the rest on your own as it sounds a lot like homework to me ;)

You can this to read your file line by line (outer loop) and iterate over the values in each line split on the char ',' (inner loop). lineIndex will always tell you which weeks values you are looking at.

try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    int lineIndex = 0;
    String line;
    while ((line = br.readLine()) != null) {
        String[] values = line.split(",");
        for (int i = 0; i < values.length; i++) {
            double value = Double.valueOf(values[i]);
            // do stuff with your number
        }
        lineIndex++;
    }
}

More in-depth explanation as to what we are doing here: We use a try-with resource block, as it ensures that the readers will get closed even if an Exception is thrown. Our BufferedReader (via the FileReader) reads the file every time we call br.readLine(). This is a line containing all the values separated by ,. So we split() the String into an array of Strings and convert each String with Double.valueOf()

You could use a Java 8 Stream consisting of the lines of the file for your tasks.

Obtain the Stream by using the Files.lines method.

Stream<String> lines = Files.lines(Paths.get(yourFileName));
//To obtain the number of weeks
long numberOfWeeks = lines.count();

Or to get the sum of each week try something along the lines of:

List<Double> weekSums = lines.map(line -> {
            List<String> asList = Arrays.asList(line.split(","));
            return asList.stream().mapToDouble(Double::parseDouble).sum();
        }).collect(Collectors.toList());

With this list of sums you can go on an calculate averages etc.

double sumOfAllWeeks = weekSums.stream().mapToDouble(Double::doubleValue).sum();
Double allWeeksAverage = weekSums.stream().collect(Collectors.averagingDouble(d -> d));
Related