170k views
1 vote
The following program contains 6 errors. Correct the errors and submit a working version of the program. The corrected version of the program should produce the following output:

Lines: 5
Words: 21
when it is run on the following input file, example.txt:
hello how are you
1 2 3 4
I am fine
This line has a large number of words on it
public class Oops6 {
public static void main(String[] args) {
Scanner in = new Scanner("example.txt");
countWords(in);
}
// Counts total lines and words in the input scanner.
public static void countWords(Scanner input) {
Scanner input = new Scanner("example.txt");
int lineCount = 0;
int wordCount = 0;
while (input.nextLine()) {
String line = input.line(); // read one line
lineCount++;
while (line.next()) { // tokens in line
String word = line.hasNext;
wordCount++;
}
}
System.out.println("Lines: " + lineCount);
System.out.println("Words: " + wordCount);
}
}

User Ohaal
by
8.4k points

1 Answer

3 votes

Final answer:

Here is the corrected version of the program that counts the total lines and words in the input scanner.

Step-by-step explanation:

The program provided has several errors. Here is the corrected version:

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Oops6 {

public static void main(String[] args) throws IOException {
File file = new File("example.txt");
FileReader fr = new FileReader(file);
Scanner in = new Scanner(fr);
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(); // read one line
lineCount++;

Scanner lineScanner = new Scanner(line);

while (lineScanner.hasNext()) { // tokens in line
String word = lineScanner.next();
wordCount++;
}

lineScanner.close();
}

System.out.println("Lines: " + lineCount);
System.out.println("Words: " + wordCount);
input.close();
}
}

User Roman Marusyk
by
7.9k points