import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Scanner; public class WordCount implements WordCountInterface { private boolean useScanner; public static void main(String[] args) { WordCount wc = new WordCount(); wc.words("WordCount.java", 10, 10); } public void setUseScanner(boolean uS) { this.useScanner = uS; } public void words(String fileName) { words(fileName, 0, -1); } public void words(String fileName, int startingWord) { words(fileName, startingWord, -1); } public void words(String fileName, int startingWord, int numWords) { int wordCount=0; try (Scanner input=new Scanner(new File(fileName))){ while (input.hasNextLine()) { // test if there is a line to read if (useScanner) { Scanner s2 = new Scanner(input.nextLine()); while (s2.hasNext()) { String s = s2.next(); if (wordCount>=startingWord && (wordCount<(startingWord+numWords) || numWords<0)) System.out.println(String.format("%4d %s", wordCount, s)); wordCount++; } s2.close(); } else { String line = input.nextLine(); String[] ss = line.split(" "); for (String s : ss) { if (wordCount>=startingWord && (wordCount<(startingWord+numWords) || numWords<0)) System.out.println(String.format("%4d %s", wordCount, s)); wordCount++; } } } } catch (FileNotFoundException e) { System.err.println("Error in opening the file:" + fileName); System.exit(1); } } }