write a method with the following signature that reads the file with specified filename and prints out the number of words and the number of lines in the file
static void countWordsAndLines (string filename)
If you have any doubts, please give me comment...
import java.util.*;
import java.io.*;
public class CountExcercise{
public static void main(String[] args) {
countWordsAndLines("test.txt");
}
static void countWordsAndLines(String filename){
String sentence, word;
int wordCount = 0, lineCount = 0;
try{
Scanner scnrFile = new Scanner(new File(filename));
while(scnrFile.hasNextLine()){
sentence = scnrFile.nextLine();
wordCount += sentence.split(" ").length;
lineCount ++;
}
scnrFile.close();
System.out.println("Number of words: "+wordCount);
System.out.println("Number of lines: "+lineCount);
}catch(FileNotFoundException e){
System.out.println("Unable to open file");
}
}
}
Get Answers For Free
Most questions answered within 1 hours.