Search code examples
javalistio

Sum of string in cloned TXT file


My task is to create a couple of methods which will process txt file and return proper input. TXT file have two lines:

1 2 3 4 5
2 7 3 4 6

My output in processed new TXT file should look like this:

 1+2+3+4+5=15
 2+7+3+4+6=22

Method to solve this :

- simple file writter - done 
- readLinesFromFile and put it inside the List<String> - done 
- take the lines from List<String> and process them and copy propper output to new TXT file. - Not Done

My main class should look like this:

   public void process(String fileName, String resultFileName) throws IOException {
        List<String> linesFromFile = fileProcessor.readLinesFromFile(fileName);
        List<String> resultLines = new ArrayList<>();
        for (String line : linesFromFile) {
            resultLines.add(NumbersProcessor.processLine(line));
        }
        fileProcessor.writeLinesToFile(resultLines, resultFileName);
    }

I stuck in method to process the resultLine so the actual third Method. I need to take the List of String proces it and paste the output to new file. To be honest I don't know how should I start.

To simplify this. I have List with this :

[1 2 3 4 5, 2 7 3 4 6] and I need to have this :

1+2+3+4+5=15, 2+7+3+4+6=22 So I need to calculate the inside strings in line and receive a SUM from it.


Solution

  • To simplify this. I have List with this :

    [1 2 3 4 5, 2 7 3 4 6] and I need to have this :

    1+2+3+4+5=15, 2+7+3+4+6=22

    You can do it as follows:

    import java.util.ArrayList;
    import java.util.List;
    
    public class Main {
        public static void main(String[] args) {
            List<String> list = List.of("1 2 3 4 5", "2 7 3 4 6");
            List<String> result = new ArrayList<String>();
            for (String s : list) {
                String[] nums = s.split("\\s+");
                int sum = 0;
                for (String n : nums) {
                    sum += Integer.parseInt(n);
                }
                result.add(String.join(",", nums) + "=" + sum);
            }
            System.out.println(result);
        }
    }
    

    Output:

    [1,2,3,4,5=15, 2,7,3,4,6=22]