Count words Learn programming Java

Lesson:

File Management


Exercise:

Count words


Objetive:

Create a java program to count the amount of words stored in a text file


Code:

public class Main
{
	public static void main(String[] args)
	{
		java.io.FileReader file = new java.io.FileReader("1.cs");
		java.io.BufferedReader fileBufferedReader = new java.io.BufferedReader(file);
		String line;
		int amountOfWords = 0;
		do
		{
			line = fileBufferedReader.readLine();
			if (line != null)
			{
				String[] words = line.split("[ ]", -1);
				amountOfWords += words.length;
			}
		} while (line != null);
		file.close();
		System.out.println("Words: " + amountOfWords);
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.