The project name of this exercise is DocStats The purpose of this assignment is
ID: 3576029 • Letter: T
Question
The project name of this exercise is DocStats
The purpose of this assignment is to learn how to work with a data file and iteration. You get more practice on how to write all of your own code and Javadoc comments.
Problem Description
This problem is inspired by the book's Problem E11.5 on page 552.
You are going to write a program that gathers statistics on a text file in a way that is similar to word processors which tell you how many characters, words, and lines you have written.
Getting Started
There is no code to copy for the assignment. You get to do it all! Don't forget to provide proper Javadoc documentation.
We are going to do this exercise by writing the object that solves the problem first (in a source file called TicketSeller.java) and then testing it using code we write into DocStats.java. Using the techniques shown on the web page titled How to Start Every Project in this Class to create a source file called DocStats.java. This is where your code will go.
Testing Your Code
Your DocStats.java should contain code for your solution to this problem. Ask the user for the name of a file (using a scanner) and outputs the statistics. A sample run is shown below:
The file "goblin.txt" is part of the project from GitHub, and should be seen in your project in Eclipse. It must be located in root directory of the project.
Once you've written your code run the code by single clicking on DocStats.java in the package explorer and selecting Run->Run from the menu or using the keyboard shortcut. Examine the output. Does it do what you want? If not, how can you modify the code to do what you want?
Explanation / Answer
DocStats.java
import java.io.File;
import java.util.Scanner;
public class DocStats {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the input file name");
String inputFile = scan.next();
System.out.println("-------------------------------");
Scanner fileInput = null;
int linecount = 0, wordcount = 0, charcount = 0;
File inFile = new File(inputFile);
try{
fileInput = new Scanner(inFile);
while(fileInput.hasNext()){
String input = fileInput.nextLine();
String words[] = input.split(" ");
for(int i=0; i<input.length(); i++){
if(Character.isLetter(input.charAt(i)))
charcount++;
}
wordcount = wordcount + words.length;
linecount++;
}
System.out.println("Number of lines : "+linecount);
System.out.println("Number of Words : "+wordcount);
System.out.println("Number of characters : "+charcount);
}
catch(Exception e){
e.printStackTrace();
}
}
}
Output:
Enter the input file name
D:\text.txt
-------------------------------
Number of lines : 3
Number of Words : 10
Number of characters : 46
text.txt
Hi, Good morning. Welcome to java world
Java
Java program
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.