Search code examples
javatext-files

How to ignore elements of a text file? - Java


For the current file I'm working on, I need to add all of the doubles into a sum while ignoring boolean values. Though giving a direct answer for this question would be nice, I would like an overall method on how to ignore certain values in the future.

For the example of the text file, it is formulated like: int "\n" boolean "\n" int "\n" boolean and so on for 20 lines (10 ints, 10 booleans).

The code that I'm being tasked to do by my professor requires that it is in method form as opposed to test class form.

Here's the code:

public double sumWithoutBoolean(File file) {
    double sum = 0;
    try {
        Scanner input = new Scanner(file);
        while(input.hasNextBoolean()) {
            boolean line2 = input.nextBoolean();
            String line = Boolean.toString(line2);
            if (line.equalsIgnoreCase("true") || line.equalsIgnoreCase("false")) {
                line = "0";
            }
            while (input.hasNextLine()) {
            }
            try {
                sum += Double.parseDouble(line);
            } catch (NumberFormatException e) {
                System.out.println("Error Found");
            }
        }
        input.close();
    } catch (FileNotFoundException e) {
        System.out.println("File Not Found.");
    }       
    return sum;
}

After running through multiple ideas, this is the one I've managed to be able to run without error though I am sure there is a more compact idea.


Solution

  • Another nicely looking implementation could be something like

       public static double sumOnlyDoubles(File file) throws IOException {
                try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                    String line;
                    double sum = 0;
                    while ((line = reader.readLine()) != null) {
                        if(line.matches("^\\d+$")){
                            sum+=Double.valueOf(line);
                    }
                }
                 return sum;
        }
    

    Here the concept is, you are reading each line of a file while it has any and with the help of a regular expression you check if the line is a digit. If it is, you add it to the sum.