Search code examples
javawhitespace

Read a text file and count the number of white spaces in the text file


I need my program in Java to get a text file, read that text file, count and reproduce the amount of white spaces in that text file

Here is the code I currently have

import java.io.File;  //import the file class
import java.io.FileNotFoundException; //import this class to handle errors
import java.util.Scanner; //import the scanner class to read the file

public class whitespaceReader {

    public static void main(String[] args) {
        try {

            File myFile = new File("aliceInWonderland.txt");

            Scanner reader = new Scanner(myFile);

            int space = 0;
            int i = 0;
            String word;

            word = reader.nextLine();

            while (i < word.length()){
                char a = word.charAt(i);

                if(a == '//tried to use empty brackets here, did not work') {
                    space++;
                }
                i++;
            }
            System.out.println("amount of white space is: " + space);

        } catch (FileNotFoundException e) {
            System.out.print("Uh oh! Something went wrong");
            e.printStackTrace();
        }
    }
}

Solution

  • You can just do it like this

    public static void main(String[] args) {
        try {
    
            File myFile = new File("aliceInWonderland.txt");
    
            Scanner reader = new Scanner(myFile);
    
            int space = 0;
            int n = 0;
            String word = "";
    
            while(reader.hasNextLine()){
                word += reader.nextLine();
            }
            n = word.length();
    
            space = word.replace(" ","").length();
            space = n - space;
            System.out.println("amount of white space is: " + space);
    
        } catch (FileNotFoundException e) {
            System.out.print("Uh oh! Something went wrong");
            e.printStackTrace();
        }
    }
    

    You just need to subtract the length of the sentence with the length of the sentence without whitespaces.

    No need for loops