Kacper Zięba
Kacper Zięba

Reputation: 43

Summing the doubles from a file

I've got a .txt file and here's its content:

1.1, 1.2, 1.3, 2.0, 1.8

1.3, aa, 4.5, 6.7, 2.1

3.5, 7.7, 9.9, 4.1, 2.1

I've got to load all lines from it, and if there'a double, sum it and show at the end.

I've written this program:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class Main3 {

    public static void main(String[] args) {

        File main3File = new File("Main3.txt");
        double sum = 0;

        try {
            Scanner scan = new Scanner(main3File);
            scan.useDelimiter(", ");
            while (scan.hasNextLine()) {
                if (scan.hasNextDouble()) {
                    sum += scan.nextDouble();
                    System.out.println(sum);
                }
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Blad");
        }

        System.out.println("Suma: " + sum);
    }
}

Here's the output:

1.1
2.3
3.5999999999996
5.6

So it sum the first three numbers, then stop and the while loop doesn't stop (if I write something under 'if', it shows without stopping). It doesn't sum the last number (1.8) and it doesn't go to the next line.

I guess it's something wrong with delimeter, right? But I don't have idea how to change it. Do you have an idea?

Upvotes: 3

Views: 282

Answers (3)

İsmail Altun
İsmail Altun

Reputation: 21

1 ) Your code has a algorithm problem.

//There is a infinite loop below. You are checking next scan and handling it if it's double
//But you keep continue to loop without passing next if it is not double, this causes infinite loop
while (scan.hasNextLine()) {
            if (scan.hasNextDouble()) {
                sum += scan.nextDouble();
                System.out.println(sum);
            }
        }

You have to add else statement and pass next like stated blow;

else{
     scan.next();
}  

2 ) You can not delimit line using

numberScanner.useDelimiter(", ");

Because you have got a multi-lined text, which scanner sees your text's end of line as a special character ("\n"). Yoo better use another way to parse, may be splitting it with String's .split method.

Hope it helps.

Upvotes: 1

Sahil Garg
Sahil Garg

Reputation: 167

Read one line at a time and split with comma to get the values. Check further if value is a double or not.

        File main3File = new File("Main3.txt");
        double sum = 0;

        try {
            Scanner scan = new Scanner(main3File);
            String line ;
            while (scan.hasNextLine()) {
                line = scan.nextLine();
                String[] values = line.trim().split("\\s*,\\s*");
                for (String value : values) {
                    try {
                        double num = Double.parseDouble(value);
                        sum = sum + num;
                        System.out.println(sum);
                    } catch (NumberFormatException e) {
                        // System.out.println("Value is not double. hence ignored");
                    }
                }
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Blad");
        }
        System.out.println("Suma: " + sum);

Let me know if you have any doubts !

Upvotes: 1

trf
trf

Reputation: 1394

The main problem is you are mixing up lines and numbers, it may be better to process them separately.

If you process the lines and numbers separately, it's easier to be sure your loop condition is correct:

Scanner lineScanner = new Scanner(file);
// Loop through lines
while (lineScanner.hasNextLine()) {
    String line = scan.nextLine();
    Scanner numberScanner = new Scanner(line);
    numberScanner.useDelimiter(", ");
    // Loop through numbers in each line
    while (numberScanner.hasNextFloat()) {
        float value = numberScanner.nextFloat();
        // do something with each value
    }
    System.out.println(sum);
}

If you really need to process the file in a single loop, then you need to use a delimiter that caters for the comma and any whitespace:

Scanner scan = new Scanner(main3File);
scan.useDelimiter("\\s*,\\s*");
while (scan.hasNext()) {
    String next = scan.next();
    try {
        float value = Float.valueOf(next);
        // do something with each value
    } catch (NumberFormatException e) {
        // not a float
    }
}

\\s* is a pattern meaning 0 or more repetitions of any whitespace character.

Upvotes: 1

Related Questions