In: Computer Science
Background: introduction to "Wrapper" classes, this is a tool or concept provided in the Java Programming Language that gives us a way to utilize native datatypes as Objects with attributes and methods. A Wrapper class in Java is the type of class which contains or the primitive data types. When a wrapper class is created a new field is created and in that field, we store the primitive data types. It also provides the mechanism to covert primitive into object and object into primitive.Working with collections, we use generally generic ArrayList<Integer> instead of this ArrayList<int>. An integer is wrapper class of int primitive type. We use a Java wrapper class because for generics we need objects, not the primitives."
Problem: Create a Word Counter application, submit WordCounter.java.
Word Counter takes input of a text file name (have a sample file in the same directory as your Word Counter application to we don't have to fully path the file). The output of our Word Counter application is to echo the file name and the number of words contained within the file.
Sample File: Hello.txt:
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// WordCounter.java
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordCounter {
// varriables to store file name and word count
private String filename;
private int wordCount;
// constructor taking file name, will throw FileNotFoundException if file is
// not found
public WordCounter(String filename) throws FileNotFoundException {
// storing file name
this.filename = filename;
// opening file in read mode
Scanner scanner = new Scanner(new File(filename));
// counting number of words in file, updating wordCount variable
while (scanner.hasNext()) {
scanner.next();
wordCount++;
}
// closing file
scanner.close();
}
// returns the words count
public int getWordCount() {
return wordCount;
}
// returns the file name
public String getFileName() {
return filename;
}
public static void main(String[] args) throws FileNotFoundException {
// setting up a scanner, reading input file name from user
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
String file = scanner.nextLine();
// creating a WordCounter object and passing filename
WordCounter counter = new WordCounter(file);
// displaying file name and number of words.
System.out.println("File name: " + counter.getFileName());
System.out.println("Number of words: " + counter.getWordCount());
}
}
/*OUTPUT*/
Enter a file name: Hello.txt
File name: Hello.txt
Number of words: 10