In this task, you will implement a program that creates an English dictionary. Y
ID: 3777372 • Letter: I
Question
In this task, you will implement a program that creates an English dictionary. You will implement a hash table to store the dictionary. The hash table will be indexed via the words in the English language. The dictionary will store the definition of the words for doing lookups after the dictionary is built.
Here are some of the key components of your implementation:
Word class
holds a word
holds the word’s definition
a key() function which returns an integer based upon converting the word to an int
See Figure 5.4 from the book for this algorithm
Dictionary class
Implements a hash table (a vector)
The hash table will start with size 101
The Dictionary class will keep track of how many Words it holds (which is size N)
The hash table uses separate chaining to resolve collisions (Chapter 5.3)
Each chain is a vector holding Words
The hash table needs to implement:void insert(Word)
Hashes the Word’s key() and adds it to the hash table if it isn’t already there
Updates (overwrites) old entry if there’s a already the same Word in the hash table
bool contains(string word)
Searches the hash table by a string.
Will need to convert the string to a key, then hash it and search the vector of Words to see if
Word delete(string word)
Finds an entry using the passed in word, erases it (vector.erase()) from the hash table, then returns it
Returns nullptr if word is not in the table
void rehash()
Is called if the table gets above a load factor (N / Table Size) of 1.0 during an insert of a new Word
At least doubles the table size then finds the next prime number for the new table size (See figure 5.22 for an example)
Example code for finding the next prime above a given integer can be found at: https://gist.github.com/alabombarda/f3944cd68dda390d25cb
Parse input file:
I have provided a file called: dictionary.json
This filename needs to be passed on the command line via argv
Example command line: ./a.out dictionary.json
That will make argv[1] be a char* to the string “dictionary.json”
Your program should detect if the filename was passed on the command line and print out help if the dictionary database wasn’t specified. For an example of this, you can go to a Linux/OSX command line and just run “ssh” with no options. It will print out a usage message.
It is in JSON format and includes our English words and definitions, one per line
You may either write your own parser, or use a JSON parsing library
Once your Dictionary class is full of our Words, it needs to print out:
1) How many words are in the dictionary
2) The current table size
3) The current load factor
After that, it goes into query mode. This will output a prompt for the user such as the one below.
Word to define:
You should be able to enter a word, hit enter and have it either print out the definition or “Word not found” if it’s not in the dictionary. I won’t ask you to do fuzzy matching for misspellings like Google does, though. Note: the dictionary.json file’s words are all uppercase, but users are going to be entering queries in whatever case they feel like. Make sure that Word == word == wOrD.
The program should exit if the user enters End of File (EOF), which is Control-D (^D). An example of detecting EOF can be found at:
http://www.cplusplus.com/reference/ios/ios/eof/
Explanation / Answer
/import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.text.*;
class JavaDictionary extends JFrame implements DocumentListener,ListSelectionListener{
//Declare variables
private JList wordlist;
private JTextField txtbox;
private JTextPane txtPane;
private Highlighter.HighlightPainter cyanPainter;
private Highlighter.HighlightPainter redPainter;
public JavaDictionary(){
super("A Simple Dictionary: English-Khmer dictionary");
//Create the JPanel panel object and make sure the components on it be aligned left
JPanel panel=new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT));
setLayout(null);/*setting the layout of displaying controls to null
will enable you to specify the locations of your controls to display */
//Create JTextField object and add DocumentListener to allow it to respond to changing value event
txtbox=new JTextField();
txtbox.getDocument().addDocumentListener(this);
//Create JTextPane object and set its font to Khmer OS with italic style and 18 in font size
Font khmerfont=new Font("Khmer OS",Font.ITALIC,18);
txtPane = new JTextPane();
txtPane.setFont(khmerfont);
//txtPane.setEditable(false);
//Create JList object that accepts the DefaultListModel listmodel as its parameter.
//Then populate this list object with the English terms read from the file by using addToList() method
DefaultListModel listmodel=new DefaultListModel();
addToList(listmodel);
wordlist=new JList(listmodel);
wordlist.setVisibleRowCount(20);
wordlist.addListSelectionListener(this);
//Add JScrollPane panel object to the list object to make sure it can be scrolled vertically.
//This object will be put in the JPanel pane object
JScrollPane scr=new JScrollPane(wordlist);
panel.add(scr);
//Define the locations and dimensions of objects then display them on the JFame window object
panel.setBounds(10,80,150,480);
txtbox.setBounds(10,40,panel.getWidth(),25);
txtPane.setBounds(panel.getWidth(),80,749,480);
add(txtbox);
add(panel);
add(txtPane);
//Add WindowListern to the JFrame to make it reacts to the closing event
addWindowListener(new Listener());
//Set the size of the JFrame window object
pack();
setSize(800,475);
//Set the background color of the JFrame window object
Container content=getContentPane();
content.setBackground(Color.PINK);
//Don't allow the user to resize the JFrame window object
setResizable(false);
//Make use the user can see the JFrame window object
setVisible(true);
}
//This method works when the window is closing
class Listener extends WindowAdapter{
public void windowClosing(WindowEvent e){System.exit(0);}
}
public void changedUpdate(DocumentEvent e){
}
//This method works when the user type text in the text box
public void insertUpdate(DocumentEvent e){
selectlist(txtbox.getText());
}
//This method works when the user removes letters in the text box
//It calls the selectlist() method to select an item of the list
// And translation text is also shown by subsequently calling the showtran() method
public void removeUpdate(DocumentEvent e){
selectlist(txtbox.getText());
}
//This method works when the user make a change to the selection of the list items
//Translation text is also shown by calling this showtran() method
public void valueChanged(ListSelectionEvent e){
showtran(wordlist.getSelectedValue());
}
public void selectlist(String text){
// Get number of items in the list
int size = wordlist.getModel().getSize();
// Select the list item that matches the text typed in the text box
//Binary search algorithm is used to speed up the search process
int index=binsearch(wordlist, text,size);
if(index!=-1) {wordlist.setSelectedIndex(index); wordlist.ensureIndexIsVisible(index);}
}
public int binsearch(JList list,String target, int n){
int i;
int pos=-1;
int found=0;
//get the middle item of the list
Object item = list.getModel().getElementAt(n/2);
String itemstr=(String)item;
//Just to make sure the length of the middle item is greater than the text typed by the user
if(itemstr.length()<=target.length())
itemstr=itemstr.concat("Learn Java to build a simple dictionary program");
if(target.compareTo(itemstr.substring(0,target.length()))<=0){//look in the first half
for(i=0;i<=n/2 && found!=1;i++){
item =list.getModel().getElementAt(i);
itemstr=(String)item;
if(itemstr.length()>=target.length())
if(target.compareTo(itemstr.substring(0,target.length()))==0){ found=1;pos=i;break;}
}
}
else{ //look in the second haft
for(i=n/2+1;i<n && found!=1;i++){
item =list.getModel().getElementAt(i);
itemstr=(String)item;
if(itemstr.length()>=target.length())
if(target.compareTo(itemstr.substring(0,target.length()))==0){ found=1;pos=i;break;}
}
}
return pos;
}
public void addToList(DefaultListModel listmodel){
try{ //catch errors if any
String text;
FileReader fr=new FileReader("dictdata.txt");
BufferedReader br=new BufferedReader(fr);
//text=br.readLine();
while ((text=br.readLine())!=null){
//Read lines of English term from the file using readLine() method
listmodel.addElement(text.substring(0,text.indexOf('_')));
}
br.close();//close file using close() method
} catch(Exception ie){System.out.println("IO problem!");ie.printStackTrace();}
}
public void showtran(Object t){
try{ //catch errors if any
txtPane.setText("");
String text;
String item=(String)t;
FileReader fr=new FileReader("dictdata.txt");
BufferedReader br=new BufferedReader(fr);
//text=br.readLine();
while ((text=br.readLine())!=null){
//Read lines of translation text from the file using readLine() method
if(item.compareTo(text.substring(0, item.length()))==0){
String st=text.substring(item.length()+1); //Display unicode characters
byte[] chars=st.getBytes();
String unitext=new String(chars,"UTF-8");
int index=unitext.indexOf('.');
//coloring translation text
highlight(unitext.substring(0,index),Color.PINK);
highlight(unitext.substring(index,unitext.length()),Color.BLUE);
break;
}
}
br.close();//close file using close() method
} catch(Exception ie){System.out.println("IO problem!");ie.printStackTrace();}
}
public void highlight(String content, Color c)
{
//Coloring text appended to the JTextPane
//The color of the text is specified by c argument
//The text is aligned in justified layout
StyleContext style = StyleContext.getDefaultStyleContext();
AttributeSet aset = style.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = style.addAttribute(aset, StyleConstants.Alignment, StyleConstants.ALIGN_JUSTIFIED);
int len = txtPane.getDocument().getLength();
txtPane.setCaretPosition(len);
txtPane.setCharacterAttributes(aset, false);
txtPane.replaceSelection(content);
}
}
//Show the dictionary window
public class EnKhDictionary{
public static void main(String[] args){
new JavaDictionary();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.