Java - not sure how to determine the number of lines in a text file and perform a calculation

problem resolved

I am starting Java and discovered some problems.

There is a file SalesData.txt that contains the amount of sales in dollars that a retail store makes every day for several weeks. Each line in the file contains seven numbers, which are daily sales for one week. Numbers are separated by a comma. The following is an example from a 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 converted String to Double and tried to compute:

  • Total sales for each week.
  • The average daily sales for each week.
  • Total sales for all weeks
  • Average weekly sales

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

+4
4

, , :

List<List<Double>> saleWeeks;

, :

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

:

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

( ) , ..

+1

WeeklySales, :

.

" " " " WeeklySales.

WeeklySales :

, .

, .

+1

, , " , ". , ;)

( ) , char ',' ( ). lineIndex , .

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++;
    }
}

, : try-with, , , Exception. BufferedReader ( FileReader) , br.readLine(). , , ,. , split() String String String Double.valueOf()

0

Java 8 Stream, .

Files.lines.

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

, , - :

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

..

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

Source: https://habr.com/ru/post/1688890/


All Articles