Solved

putting read file contents into a hash table

Posted on 2003-11-05
10
818 Views
Last Modified: 2012-08-13
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 );
    }

}
0
Comment
Question by:DAJones
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
10 Comments
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 9691286
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
 
LVL 92

Expert Comment

by:objects
ID: 9691293
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
 
LVL 3

Expert Comment

by:savalou
ID: 9691362
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
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 

Author Comment

by:DAJones
ID: 9691375
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
 
LVL 92

Expert Comment

by:objects
ID: 9691413
> the compiler cant "resolve symbol  location class StreamTokenizer

The code i posted doesn't use a StreamTokenizer??
0
 
LVL 92

Expert Comment

by:objects
ID: 9691420
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
 
LVL 92

Expert Comment

by:objects
ID: 9691426
         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
 
LVL 92

Expert Comment

by:objects
ID: 9691432
you can then lookup the weight of an element using:

Double weight = (Double) lookup.get(element);
0
 
LVL 92

Expert Comment

by:objects
ID: 9691474
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
 
LVL 92

Expert Comment

by:objects
ID: 9890248
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Android development question 2 108
eclipse console opening separately 2 48
Java program running SQL query 5 62
running on tomcat not jboss eap 7.0 3 52
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This video teaches viewers about errors in exception handling.
Suggested Courses

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question