Link to home
Start Free TrialLog in
Avatar of DAJones
DAJones

asked on

putting read file contents into a hash table

I just opened a new can of worms. I have a file reader that reads integers, but now I need it to put  a string, and a number  into a hash table. I havs a txt file:
4
H 1.007
O 15.9
S 32.068
AL 26.9

the 4 at the top is the number of elements  have.
the leters are the elements, and the number represents an atomic weight.How can I modify this?
Thanks
DAJones

I have the hashTable, ans the HasTest2 code:

public class HashTable
{  
  private HashEntry[] array;
  private int currentSize;
  private int occupied;
  private int modCount;
  private static final int DEFAULT_TABLE_SIZE = 101;
   
  private class HashEntry implements java.io.Serializable
  {    
    public Object element;
    public boolean isActive;                                          
       
    public HashEntry(Object e)
    {
      this(e, true);
    }
   
       
    public HashEntry(Object e, boolean i)
    {
      element = e;
      isActive = i;
    }
  }
   
  private void allocateArray(int arraySize)
  {
    array = new HashEntry[arraySize];
  }
   
   private static int nextPrime( int n )
        {
            if( n % 2 == 0 )
                n++;

            for( ; !isPrime( n ); n += 2 )
                ;

            return n;
        }
   
        private static boolean isPrime( int n )
        {
            if( n == 2 || n == 3 )
                return true;

            if( n == 1 || n % 2 == 0 )
                return false;

            for( int i = 3; i * i <= n; i += 2 )
                if( n % i == 0 )
                    return false;

            return true;
        }
   
    public HashTable( )
    {
        allocateArray( DEFAULT_TABLE_SIZE );
        clear( );
    }
       
     
    public int size( )
    {
        return currentSize;
    }
      public boolean contains( Object x )
    {
        return isActive( array, findPos( x ) );
    }
      private static boolean isActive( HashEntry [ ] arr, int pos )
    {
        return arr[ pos ] != null && arr[ pos ].isActive;
    }
   
    public Object getMatch( Object x )
    {
        int currentPos = findPos( x );

        if( isActive( array, currentPos ) )
            return array[ currentPos ].element;
        return null;
    }
      public boolean remove( Object x )
    {
        int currentPos = findPos( x );
        if( !isActive( array, currentPos ) )
            return false;
       
        array[ currentPos ].isActive = false;
        currentSize--;
        modCount++;    
       
        if( currentSize < array.length / 8 )
            rehash( );
   
        return true;
    }
      public void clear( )
    {
        currentSize = occupied = 0;
        modCount++;
        for( int i = 0; i < array.length; i++ )
            array[ i ] = null;
    }
   
      private int findPos( Object x )
    {
        int collisionNum = 0;
        int currentPos = ( x == null ) ? 0 : Math.abs( x.hashCode( ) % array.length );

        while( array[ currentPos ] != null )
        {
            if( x == null )
            {
                if( array[ currentPos ].element == null )
                    break;
            }
            else if( x.equals( array[ currentPos ].element ) )  
                break;
           
            currentPos += 2 * ++collisionNum - 1;  // Compute ith probe
            if( currentPos >= array.length )       // Implement the mod
                currentPos -= array.length;
        }

        return currentPos;
    }
       
    public boolean add(Object x)
    {
      int currentPos = findPos(x);
      if(isActive(array, currentPos))
        return false;
      array[currentPos] = new HashEntry(x, true);
      currentSize++;
      occupied++;
      modCount++;
      if(occupied > array.length / 2)
        rehash();
      return true;
    }
    private void rehash( )
    {
        HashEntry [ ] oldArray = array;

            // Create a new, empty table
        allocateArray( nextPrime( 4 * size( ) ) );
        currentSize = 0;
        occupied = 0;
            // Copy table over
        for( int i = 0; i < oldArray.length; i++ )
            if( isActive( oldArray, i ) )
                add( oldArray[ i ].element );
    }
   
}


import java.io.*;
public class HashTest2 {

    /**
    * @param args the command line arguments
    */
    public static void main (String args[]) {
       
       // Verify the correct number of command-line parameters
       // have been passed as arguments, otherwise, print
       // an error message and exit.
       if ( args.length < 2 ) {
          System.out.println( "usage: java HashTest <input> <output>" );
          System.out.println();
          System.out.println( "<input>  - name of the input file" );
          System.out.println( "<output> - name of the output file" );
          System.exit( 0 );
       }
         
       
       BufferedReader br;
       BufferedWriter bw;
       PrintWriter    pw;
       String         line;
       HashTable      tLine = new HashTable(  );
       Element []   table;
       
       try{
          // Attempt to open the specified input and output files.
          br = new BufferedReader( new FileReader( args[0] ) );
          pw = new PrintWriter( new FileWriter( args[1] ) );
         
          pw.println( "Linear Probing Table" );

          // Read the first line of the input file.
          line = br.readLine();
         
          // While there is still input in the input file
          while ( line != null ) {
              // Read a value from the input file, convert it to an Integer,
              // and put it into the hash table.
              //Integer item = new Integer( Integer.parseInt( line ) );
              String item = new String( line );
              tLine.add( item );
              line = br.readLine();
          }

          // Write the hash table built to the output file.
          pw.println( tLine );

          // Close the input and output file, to save changes.
          br.close();
          pw.close();
         
       }
       catch ( IOException ioe ) {
       }

          System.exit( 0 );
    }

}
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Though looking at it, exactly what is it you want to do with the hash table?
And what problems do you have if just adding the line as you currently do?
Avatar of savalou
savalou

Modify your HashTest2 main method as follows:
         // Read the first line of the input file.
         line = br.readLine();
          int linecount = Integer.parseInt(line);
         for (int i = 0; i < linecount; i++) {
             line = br.readLine();
             // Read a value from the input file, convert it to an Integer,
             // and put it into the hash table.
             //Integer item = new Integer( Integer.parseInt( line ) );
             int pos = line.indexOf(" ");
             Element el = new Element();
             el.setName(line.substring(0, pos));
             el.setWeight(Double.parseDouble(line.substring(pos + 1)));
             tLine.add( el );
         }
          // Write the hash table built to the output file.
         pw.println( tLine );

I assume you have an Element class defined somewhere and it will have the setter methods.  That's pretty much it.
Avatar of DAJones

ASKER

This is only part of my problem, I have to make a program that reads two files. 1st file is the periodic table which has to go into a hash table, and the second one reads a file containing chemical formulas, and the program has to make a txt file that lists the molecular weight totals. ( the third argument ) Thanks for gettting back so quickly by the way. I tried what you wrote, but it doesnt compile. the compiler cant "resolve symbol  location class StreamTokenizer
> the compiler cant "resolve symbol  location class StreamTokenizer

The code i posted doesn't use a StreamTokenizer??
Why are you using your own hash table? Is this a corsework requirement?
You would be better off using a Map instead of your hash table to allow you to look up the weight by element.
         Hashtablelookup = new Hashtable();
          // While there is still input in the input file
          while ( (line=br.readLine()) != null ) {
           StringTokenizer st = new StringTokenizer(line);
           String code = st.nextToken();
           Double weight = new Double(st.nextToken());
           lookup.put(code, weight);
         }
you can then lookup the weight of an element using:

Double weight = (Double) lookup.get(element);
Using your hash table with the Element class you I posted above you would use the following to find an element:

String elementcode = "O";
Element el = (Element) tLine.getMatch(elementcode);
double weight = el.Weight;

PS. Add the following import to the Element class:

import java.util.*;