programming in java In this assignment, you\'ll write a program which reads a te
ID: 3831925 • Letter: P
Question
programming in java
In this assignment, you'll write a program which reads a text file, and prints a histogram of its word sizes. So, for example, the historgram should show the number of words of length 1, of length 2, etc., up to the number of words of length n, where n is some constant defined in your program.
To obtain text files that are suitably long, you could try Project Gutenberg, a site containing thousands of free books available in several different formats (for this assignment, you're interested in files in plain text format).
For your convenience, a mirrored local copy of a book is here.
Attach a Scanner to a File object associated with the file, and read the file, noting the length of each word. Hint: to tell your Scanner to use any non-word characters as a delimiter, you could do something like:
Scanner fin = new Scanner(new File(filename));
fin.useDelimiter("\W+");
(It's not necessary for this assignment, but if you're curious, other possibilities for patterns may be found in the java.util.regex.Pattern API page.)
Once you've counted the number of words of each size, the program should print a histogram. When I run my program on the Autobiography of Benjamin Franklin, it produces the following histogram:
some notes
Do not hard code the name of the file to read. This, instead should be determined at runtime. Either prompt the user for the name of the file (or pass it as a command-line argument). If there is an error opening the file, the program should print an error message and exit. This should be done by handling FileNotFoundException.
We don't know in advance how large the file will be, or the count of words (so, for example, we won't know how long the longest line of '*'s will be), and we don't want the histogram to have lines which wrap. For this reason, the number of words that the '*' represents should be determined only after you've counted all of the words in the file.
Good programming style will play a part in your final grade for the assignment. Please be sure to break up the code into separate functions, and document your code.
Explanation / Answer
package myProject;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
//Class FileHistogram definition
public class FileHistogram
{
//Data member to store all the words in the file
String completeWords[];
//To store total number of words available in file
int totalWord = 0;
//To store length of each word
int wordLength[] = new int[15];
//Method to read file
void ReadFile()
{
int c = 0;
//Scanner class object created to accept file name from console
Scanner input = new Scanner(System.in);
//Scanner class object for file reading
Scanner fileRead;
//Variable to store file name
String fileName;
//Accept the file name
System.out.println("Enter a file name to read");
fileName = input.nextLine();
//Open the file
File file = new File(fileName);
//Try block begin
try
{
//Read the file
fileRead = new Scanner(file);
//Check whether the file contains data or not
while (fileRead.hasNextLine())
{
//Read the word
fileRead.next();
//Increase the counter to number of words in the file
totalWord++;
}//End of while
//Creates an String array with the total number of words in the file
completeWords = new String[totalWord];
//Close the file
fileRead.close();
//Re - open the file
fileRead = new Scanner(file);
//Check whether the file contains data or not
while (fileRead.hasNextLine())
{
//Read a word from the file and store it in the String array
completeWords[c] = fileRead.next();
//Increase the counter by one
c++;
}//End of while
//Close the file
fileRead.close();
} //End of try block
//Catch to handle file not found exception
catch (FileNotFoundException e)
{
System.out.println("File Not Fount");
}//End of catch
}//End of method
//Method to count length of each word and store it in wordLength array
void countLength()
{
int len;
//Loops till total number of words
for(int x = 0; x < totalWord; x++)
{
//Stores the length of each word
len = completeWords[x].length();
//Passes the length of each word to increase the counter for each word length
switch(len)
{
case 1:
wordLength[0]++;
break;
case 2:
wordLength[1]++;
break;
case 3:
wordLength[2]++;
break;
case 4:
wordLength[3]++;
break;
case 5:
wordLength[4]++;
break;
case 6:
wordLength[5]++;
break;
case 7:
wordLength[6]++;
break;
case 8:
wordLength[7]++;
break;
case 9:
wordLength[8]++;
break;
case 10:
wordLength[9]++;
break;
case 11:
wordLength[10]++;
break;
case 12:
wordLength[11]++;
break;
case 13:
wordLength[12]++;
break;
case 14:
wordLength[13]++;
break;
default:
wordLength[14]++;
}//End of switch
}//End of for loop
}//End of method
//Method to Display histogram
void displayHistogram()
{
//Limit is 10
final int MAX = 5;
int times;
//Displays the heading
System.out.print("Len Count " );
//Loops till wordLength array length
for(int x = 0; x < wordLength.length; x++)
{
//Initializes times to zero
times = 0;
//If worLength counter value is greater than limit MAX
if(wordLength[x] > MAX)
//Divide the value of wordLength x position by MAX and store the quotient
times = wordLength[x] / MAX;
/*else
times = wordLength[x];*/
System.out.print((x + 1) + " " + wordLength[x]);
//Displays the * up to times value
for(int y = 0; y < times; y++)
System.out.print("*");
System.out.println();
}//End of for loop
}//End of method
//Main Method
public static void main(String[] args)
{
//Creates the file object
FileHistogram fh = new FileHistogram();
//Calls the methods
fh.ReadFile();
fh.countLength();
fh.displayHistogram();
}//End of main
}//End of class
Data.txt File Contents
done eat working voice test surprise organization
public turing delete age targate doing testing eye
occupation target ask agree spend support play
positive private protected danger delegate support
sensitive dealing dumb daring asking agreement
elephant eager temple come computer fox fire final
fix end agent umbrella finger find payment pot pin
animal auto an a is was and the so then if else
there vowel consonant president poor weak rich so
soon like in on at sugar cane up down to come eat
eye ear nose moth day night fresh and check soon so
tear leg hand finger nail lab code list for from any
one who whom what name no yes from to
Output:
Enter a file name to read
Data.txt
Len Count
1 1
2 13**
3 24****
4 31******
5 13**
6 11**
7 8*
8 6*
9 5
10 1
11 0
12 1
13 0
14 0
15 0
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.