Solved

putting read file contents into a hash table

Posted on 2003-11-05
10
813 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
HashTable highest marks enumeration alternative 9 47
jdbc error in jsp application 20 71
ejb entity bean example issue 2 25
Glassfish admin console not working 1 56
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn different types of Android Layout and some basics of an Android App.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

762 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