JAVA - reading a text file, recognizing new lines

advertisements

I have a task to read a text file with several lines, after that I need to count every character's UNICODE value, so the sum of "hello" is 532 and for "how are you" is 1059 and so on, every string begins on new line in the .txt document and so far so good. But for every line I need to print only its own value, and the way my code works, it adds every line's value and I cant get my head around a way to stop it when the end of the lxtine comes so it looks something like: *read line *count char values *add up *print them *start over for the next line, and so

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.lang.String;
import java.util.Arrays;

public class SumLines {

    public static void main(String[] args) {

        String filePath = "/home/lines.txt";
        String readLine;
        int sum = 0;

        try (BufferedReader bufferedReader = new BufferedReader(new    FileReader(filePath))) {
            while ((readLine = bufferedReader.readLine()) != null) {
                char[] array = new char[readLine.length()];
                System.out.println(readLine);

                for (int i = 0; i < readLine.length(); i++) {

                    Arrays.fill(array, readLine.trim().charAt(i));
                    sum += (int) array[i];

                    System.out.print(sum + " ");
                }
            }
        } catch (IOException e) {
            System.out.println("Error.\n Invalid or missing file.");
            e.printStackTrace();
        }
       System.out.println("\n*** final " + sum);
    }
}


If I understood correctly, for the input:

hello
how are you

You would like to get something like this as output:

hello 532
how are you 1059

*** final 1591

For this, you need to make some modifications to your code:

  • In addition to calculating the sum of characters values per line, keep another sum of the total of all lines
  • For each input line, print the line followed by the sum of character values
  • You don't need an array at all
  • It's better to trim the input line once, instead of for every character

Like this:

    int total = 0;

    try (BufferedReader bufferedReader = new BufferedReader(new    FileReader(filePath))) {
        String readLine;
        while ((readLine = bufferedReader.readLine()) != null) {
            String trimmed = readLine.trim();
            int sum = 0;
            for (int i = 0; i < trimmed.length(); i++) {
                sum += (int) trimmed.charAt(i);
            }
            System.out.println(readLine + " " + sum);
            total += sum;
        }
    } catch (IOException e) {
        System.out.println("Error.\n Invalid or missing file.");
        e.printStackTrace();
    }
    System.out.println("\n*** final " + total);