settingsAccountsettings
Menusettings

Q: Sum lines - Java Task

+8 votes

Write a program that reads a text file and prints on the console the sum of the ASCII symbols of each of its lines. Use BufferedReader in combination with FileReader.

sum lines in Java

asked in Java category by user nikole
edited by user golearnweb

2 Answers

+2 votes

Here is my solution:

import java.io.*;

public class Pr_01_SumLines {
    public static void main(String[] args) throws IOException {
        File lines = new File("resources/lines.txt");
        BufferedReader reader = new BufferedReader(new FileReader(lines));

        String line = reader.readLine();

        while (line != null) {
            int symbolsTotalCount = 0;
            for (int i = 0; i < line.length(); i++) {
                symbolsTotalCount += line.charAt(i);
            }
            System.out.println(symbolsTotalCount);
            line = reader.readLine();
        }
        reader.close();
    }
}

 

answered by user Jolie Ann
+1 vote

Here's mine - wiht try-catch block - and particular output on FileNotFoundException and IOException exceptions:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Locale;
 
public class SumLines {
 
    public static void main(String[] args) {
        Locale.setDefault(new Locale("en", "EN"));
 
        try (BufferedReader reader = new BufferedReader(new FileReader("resources/lines.txt"))) {
            String line = reader.readLine();
 
            while (line != null) {
                int symbolTotalCount = 0;
                for (int i = 0; i < line.length(); i++) {
                    symbolTotalCount += line.charAt(i);
                }
                System.out.println(symbolTotalCount);
 
                line = reader.readLine();
            }
 
            reader.close();
        } catch (FileNotFoundException fileNotFoundEx) {
            System.out.print("File not found.");
        } catch (IOException inputOutputEx) {
            System.out.print("Invalid file.");
        }
    }
}

 

answered by user matthew44
...