Exercise : countWords errors practice-it

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Counts the total lines and words in the given input scanner.
public static void countWords(Scanner input) {
    Scanner input = new Scanner(new File("example.txt"));
    int lineCount = 0;
    int wordCount = 0;
    
    while (input.nextLine()) {
        String line = input.line();       // read one line
        lineCount++;
        while (line.next()) {             // count tokens in line
            String word = lineScan.hasNext;
            wordCount++;
        }
    }
}

The above attempted solution to Practice-It problem "countWords" has 5 errors. Open Practice-It from the link above, copy/paste this code into it, and fix the errors. Complete the code so that it passes the test cases.

Exercise - answer

  1. line 3: should not declare another Scanner for the file
  2. line 7: nextLine should be hasNextLine
  3. line 8: line should be nextLine
  4. line 10: need a second line Scanner to read the tokens of each line
  5. line 11: hasNext should be next()
  6. line 14: need to add 3 println statements to print line/word stats

Exercise - solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Counts the total lines and words in the given input scanner.
public static void countWords(Scanner input) {
    Scanner input = new Scanner(new File("example.txt"));
    int lineCount = 0;
    int wordCount = 0;
    
    while (input.hasNextLine()) {
        String line = input.nextLine();   // read one line
        lineCount++;
        Scanner lineScan = new Scanner(line);
        while (lineScan.hasNext()) {      // count tokens in line
            String word = lineScan.next();
            wordCount++;
        }
    }
    
    System.out.println("Total lines = " + lineCount);
    System.out.println("Total words = " + wordCount);
    System.out.printf("Average words per line = %.3f\n", (double) wordCount / lineCount);
}