1

I have a rather silly question but I couldn't find a fix anywhere. I have a scanner set up that prints lines that are in appropriate format. Here is my while loop within that program:

while (fileScan.hasNextLine()){
        String line = null;
        line = fileScan.nextLine();
        String[] element = line.split (":");

            if(line.matches("\\w+\\s?\\w+?\\s?\\w+?\\s[:]\\s\\w+\\s?\\w+?\\s?\\w+?\\s[:]\\s\\d+\\s[:]\\s\\d+")){
                   count++;
                   System.out.println(element[0]+"["+element[2]+"]\t"+"|"+element[1]+"["+element[3]+" ]");

            } else {
            invalidLines++;
                System.out.println("Line declined.");

            }
    }

What would I need to do in order to keep adding all the values of element[2] (assuming they are all strings, I do understand that converting them to int is necessary) and print a single line at the end with a total sum of added element[2]'s.

If you could just simply point me in the right direction I would highly appreciate it.

1 Answer 1

3

You could add a sum field before you start scanning through the file, and then when a line match occurs, do sum += Integer.parseInt(element[2]); and after you're done scanning, print the value of sum.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I had to trim the values because it was throwing an Exception error otherwise so sum +=Integer.parseInt(element[2].trim());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.