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 );
    }

}
DAJonesAsked:
Who is Participating?
 
objectsCommented:
create a new class to represent an element and add that to your has table:

public class Element
{
   String Code = null;
   double Weight = 0;

   public Element(String line)
   {
      StringTokenizer st = new StringTokenizer(line);
      Code = st.nextToken();
      Weight = Double.parseDouble(st.nextToken());
   }

   public int hashCode()
   {
      return Code.hashCode();
   }
}
0
 
objectsCommented:
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?
0
 
savalouCommented:
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.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
DAJonesAuthor Commented:
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
0
 
objectsCommented:
> the compiler cant "resolve symbol  location class StreamTokenizer

The code i posted doesn't use a StreamTokenizer??
0
 
objectsCommented:
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.
0
 
objectsCommented:
         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);
         }
0
 
objectsCommented:
you can then lookup the weight of an element using:

Double weight = (Double) lookup.get(element);
0
 
objectsCommented:
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.*;


0
 
objectsCommented:
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.