1. Use a text editor such as Wordpad or Notepad to create a file with one word per line. These words will to be loaded by the Glossary object.
2. Write a constructor for the Glossary class that accepts the name of a file (a string) as its only argument. The constructor should:
a. open the file (remember to use a try-catch statement here)
b. read each line of data (a word)
c. add each word to the collection of words.
3. Write a toString method that returns a string which when printed will appear as follows:
4. Write a method named letterOccurrence that accepts a letter as its parameter. The method should return the number of words in the glossary beginning with the letter accepted. Ignore the case.
5. Write a driver class (or modify the one you already have) to:
a. Input the name of the file
b. Create the Glossary object
c. Display the words in the glossary
d. Input a letter. The number of words starting with that letter is to be counted
e. Display the number of words starting with that letter entered in 5(d) above.
Glossary Class:
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Glossary {
private String word;
ArrayList<String> wordlist = new ArrayList<String>();
Glossary(String fname)
{
try
{
Scanner fileScan;
fileScan = new Scanner (new File(fname));
while (fileScan.hasNext())
{
word = fileScan.nextLine();
wordlist.add(word);
}
}
catch (IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
public String toString()
{
String result;
int index = 0;
result = "# Word\n";
result+="_________________________________________________\n";
while (index < wordlist.size())
{
result+=(index+1)+" "+wordlist.get(index)+"\n";
index++;
}
return result;
}
public int letterOccurrence(char letter)
{
int index = 0;
int result = 0;
while (index < wordlist.size())
{
char l = wordlist.get(index).toUpperCase().charAt(0);
if(l == letter)
{
result++;
}
index++;
}
return result;
}
}
GlossaryDriver:
import java.io.*;
import java.util.Scanner;
public class GlossaryDriver {
public static void main(String[] args)throws IOException {
Glossary gl = new Glossary("words.txt");
System.out.print(gl.toString());
System.out.print("Enter a letter: ");
Scanner scan= new Scanner (System.in);
String p = scan.nextLine();
System.out.print("\n\nNumber of Occurances for "+ p+ " is : "+gl.letterOccurrence(p.charAt(0)));
}
}