Question

Java using data structures The objective is to create your own Hash Table class to hold...

Java using data structures

The objective is to create your own Hash Table class to hold a list of employees and their ID numbers. I've provided the TableEntry class which will be each data object in the hash table. The list of employees will be provided as a .txt file and must be read with the code. please create a .txt file called Employees.txt with the info provided so that the java code can read it in.

Employees.txt: (No WhiteSpace between lines)

135,John Peterman

160,Joe Divola

101,David Putty

68,Jerry Seinfeld

225,George Costanza

100,Elaine Benes

200,Cosmo Kramer

TableEntry.java:

public class TableEntry {

private int key;

private String value;

TableEntry(int key, String value) {

this.key = key;

this.value = value;

}

public int getKey() {

return key;

}

public String getValue() {

return value;

}

}

Directions:

1) Your hash table class should have an array of TableEntry objects that store the key(id number) and value(name)

2) Use the Linear probing technique to handle collisions when you add or search the table

3) You hash function code should be in its own method, NOT in your main method.

You don't have to worry about removing data from the table or keeping track of “Empty Since Start” or “Empty After Removal” buckets. Treat all empty buckets as "Empty since start".

You must have these 3 classes: Main.java, HashTable.java, TableEntry.java

Flow of the main program:

Create an instance of your hash table class in the main class.

Read in the Employees.txt file and store the names and ID numbers in your hash table using the SIMPLE modulo operator (%) hash function: "key%N" where N is the size of your array.

After you stored all the data in the table, print out all the employee names and their corresponding id numbers.

Pick a random employee's ID number and then search for them in the hash table and retrieve their name, print it to the screen.

must read in data from text file Employees.txt (No Whitespace between entries, just next line between entries)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1) tableentry.java

package customhashtable;

public class TableEntry {
  
   private int key;
   private String value;

   TableEntry(int key, String value) {
       this.key = key;
       this.value = value;
   }

   public int getKey() {
       return key;
   }

   public String getValue() {
       return value;
   }

   public void setValue(String value) {
       this.value = value;
   }
}

2) hashtable.java

package customhashtable;

public class HashTable {

   private int currentSize, maxSize;
   private TableEntry[] entries;

   /** Constrctor **/
   HashTable(int capacity) {
       this.maxSize = capacity;
       currentSize = 0;
       entries = new TableEntry[maxSize];
   }

   /** Function to clear hash table **/
   public void makeEmpty()

   {
       currentSize = 0;
       entries = new TableEntry[maxSize];

   }

   /** Function to get size of hash table **/
   public int getSize() {
       return currentSize;
   }

   /** Function to check if hash table is full **/
   public boolean isFull()

   {
       return currentSize == maxSize;
   }

   /** Function to check if hash table is empty **/
   public boolean isEmpty() {
       return getSize() == 0;
   }

   /** Function to check if hash table contains a key **/
   public boolean contains(int key)

   {
       return get(key) != null;
   }

   /** Function to insert key-value pair **/
   public void insert(int key, String value)

   {
       int tmp = key % maxSize;
       int i = tmp;
      
       do {
           if (entries[i] == null) {
               entries[i] = new TableEntry(key, value);
               currentSize++;
               return;
           }

           if (entries[i].getKey() == key) {
               entries[i].setValue(value);
           }

           i = (i + 1) % maxSize;

       } while (i != tmp);

   }

   /** Function to get value for a given key **/
   public String get(int key) {

       int i = key % maxSize;

       while (entries[i] != null) {
           if (entries[i].getKey() == key)
               return entries[i].getValue();

           i = (i + 1) % maxSize;
       }
       return null;
   }

   /** Function to remove key and its value **/

   public void remove(int key)

   {

       if (!contains(key))
           return;
       /** find position key and delete **/

       int i = key % maxSize ;

       while (!(key==entries[i].getKey()))
           i = (i + 1) % maxSize;
      
       entries[i] = null;

       currentSize--;

   }

  
   /** Function to print HashTable **/

   public void printHashTable() {
       System.out.println("\nHash Table: ");

       for (int i=0;i<maxSize;i++)
           if (entries[i] != null)
               System.out.println(entries[i].getKey() + " " + entries[i].getValue());
       System.out.println();

   }

}

3) main.java

package customhashtable;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class Main {

   public static void main(String[] args)

   {

       Scanner sc = new Scanner(System.in);

       System.out.println("Hash Table Test\n\n");

       System.out.println("Enter size");

       // creating hashtable with given size
       HashTable htable = new HashTable(sc.nextInt());
      
       // File Properties
      
       BufferedReader in;
       String file="employees.txt";
      
      
       char ch;

       /** Perform HashTable operations **/

       do

       {

           System.out.println("\nHash Table Operations\n");

           System.out.println("0. access new data from file");
          
           System.out.println("1. insert ");

           System.out.println("2. remove");

           System.out.println("3. get");

           System.out.println("4. clear");

           System.out.println("5. size");

           int choice = sc.nextInt();

           switch (choice)

           {
           case 0: {
              
                  try { //Accessing file information
                          in = new BufferedReader(new FileReader(file));
                        String str;
                        int count=0;
                      
                        //Counting number of entries
                        while ((str = in.readLine())!= null) {
                           count++;
                        }
                      
                        in.close();
                      
                        //Reopening file to start from begining
                        in = new BufferedReader(new FileReader(file));
                      
                        //creating hashtable base on count value
                        htable = new HashTable(count);
                      
                        while ((str = in.readLine())!= null) {
                            String[] linearray=str.split(",");
                          
                            int key=Integer.parseInt(linearray[0].trim());
                            String value= linearray[1].trim();
                         
                            htable.insert(key, value);
                        }
                 
                        in.close();
                    } catch (IOException e) {
                        System.out.println("File Read Error");
                        break;
                    }
                  System.out.println("Table created..");
                  break;
           }
          
          
           case 1: {
              
               if(htable.isFull()){
                   System.out.println("List is Full...");
                   break;
               }

               int key;
               String value;
               System.out.println("Enter key : ");
               key = sc.nextInt();

               System.out.println("Enter value : ");
               value = sc.next();

               htable.insert(key, value);
              
               System.out.println("inserted...");
               break;

           }

           case 2: {
              
               System.out.println("Enter key");
               htable.remove(sc.nextInt());
               System.out.println("removed...");
               break;

           }

           case 3:{
              
               System.out.println("Enter key");
               System.out.println("Value = " + htable.get(sc.nextInt()));
              
               break;
           }
          
           case 4:
           {
               htable.makeEmpty();
               System.out.println("Hash Table Cleared\n");
               break;
           }
           case 5:
           {
               System.out.println("Size = " + htable.getSize());
               break;
           }
          
           default:
           {
               System.out.println("Wrong Entry \n ");
               break;
           }
           }

           /** Display hash table **/

           htable.printHashTable();

           System.out.println("\nDo you want to continue (Type y or n) \n");

           ch = sc.next().charAt(0);

       } while (ch == 'Y' || ch == 'y');
   }
}

Add a comment
Know the answer?
Add Answer to:
Java using data structures The objective is to create your own Hash Table class to hold...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • IN JAVA USING ECLIPSE The objective of this assignment is to create your own hash table...

    IN JAVA USING ECLIPSE The objective of this assignment is to create your own hash table class to hold employees and their ID numbers. You'll create an employee class to hold each person's key (id number) and value (name). Flow of the main program: Create an instance of your hash table class in your main method. Read in the Employees.txt file and store the names and ID numbers into Employee objects and store those in your hash table using the...

  • This should be in Java Create a simple hash table You should use an array for...

    This should be in Java Create a simple hash table You should use an array for the hash table, start with a size of 5 and when you get to 80% capacity double the size of your array each time. You should create a class to hold the data, which will be a key, value pair You should use an integer for you key, and a String for your value. For this lab assignment, we will keep it simple Use...

  • Following class is only part of my program that uses a hash table to simulate a...

    Following class is only part of my program that uses a hash table to simulate a market's client database, client class is my main class which asks user to input client names and then creates a hash table which then users can look up client names. wasn't able to upload everything as it is too much code, but what I need is to modify my client class instead of me inputting data line by line, the program should read from...

  • The task of this project is to implement in Java Hash Table structure using Linear Probing...

    The task of this project is to implement in Java Hash Table structure using Linear Probing Collision Strategy.   You can assume that no duplicates or allowed and perform lazy deletion (similar to BST). Specification Create a generic class called HashTableLinearProbe <K,V>, where K is the key and V is the value. It should contain a private static class, HashEntry<K,V>. Use this class to create array to represent Hashtable:             HashEntry<K,V> hashtable[]; Implement all methods listed below and test each method...

  • Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into...

    Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into hash table we insert at an index calculated by the key modulo the array size, what would happen if we instead did key mod (array_size*2), or key mod (array_size/2)? (Describe both cases). Theory answer Here Change your hashtable from the labs/assignments to be an array of linkedlists – so now insertion is done into a linkedlist at that index. Implement insertion and search. This...

  • Programming 5_1: Create a Java class named <YourName>5_1 In this class create a main method...

    Programming 5_1: Create a Java class named <YourName>5_1 In this class create a main method, but for now leave it empty. Then write a Java method getAverage which takes an array of integers as it’s argument. The method calculate the average of all the elements in the array, and returns that average. The method should work for an array of integers of any length greater than or equal to one. The method signature is shown below: public static double getAverage(...

  • Using Java 1.) Write Integers to a File – This time build a class WriteInts. This...

    Using Java 1.) Write Integers to a File – This time build a class WriteInts. This class, when instantiated, will create a new file and write an array of integers to this new file. All the code to write the data to the file goes in the Constructor. [i.e.   // This code goes in main() int myArr[] = {16, 31, 90, 45, 89};         WriteInts wi = new WriteInts(“mydata.dat”, myArr);   ] 2.) Read Integers from a File – This time...

  • using java File Details – Build a class called FileDetails.java. When you instantiate this class and...

    using java File Details – Build a class called FileDetails.java. When you instantiate this class and give it a filename, it will report back the size of the file, whether the file is Readable and whether the file is Writeable; plus any other file information that you might deem important. This cd goes in main FileDetails fd=newFileDetails(“anyfile.doc”); All other code goes in the constructor. Write a String to a File using PrintStream – This time build a class WriteString. This...

  • (JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text...

    (JAVA) Use the Pet.java program from the original problem (down below) Compile it. Create a text file named pets10.txt with 10 pets (or use the one below). Store this file in the same folder as your “class” file(s). The format is the same format used in the original homework problem. Each line in the file should contain a pet name (String), a comma, a pet’s age (int) in years, another comma, and a pet’s weight (double) in pounds. Perform the...

  • (To be written in Java code) Create a class named CollegeCourse that includes the following data...

    (To be written in Java code) Create a class named CollegeCourse that includes the following data fields: dept (String) - holds the department (for example, ENG) id (int) - the course number (for example, 101) credits (double) - the credits (for example, 3) price (double) - the fee for the course (for example, $360). All of the fields are required as arguments to the constructor, except for the fee, which is calculated at $120 per credit hour. Include a display()...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT