Question:
How to write a program that counts the number of words and lines in a file?
Code:
import java.util.*; import java.io.*; public class CountWords { public static void main(String[] args) throws FileNotFoundException { File file = new File("example.txt"); Scanner in = new Scanner(new FileInputStream(file)); countWords(in); } // Counts total lines and words in the input scanner. public static void countWords(Scanner input) { int lineCount=0; int wordCount=0; while(input.hasNextLine()) { String line = input.nextLine(); lineCount++; String str[] = line.split((" ")); for (int i=0;i<str.length;i++) { if (str[i].length()>0) { wordCount ++; } } } System.out.println("Lines: " + lineCount); System.out.println("Words: " + wordCount); } }
Output:
$ cat example.txt this is line one this is line two this is line three $ java CountWords Lines: 3 Words: 12