Results 1 to 14 of 14
  1. #1
    li_bi is offline Member
    Join Date
    Feb 2010
    Posts
    7
    Rep Power
    0

    Smile Problems with HashMaps

    Hello

    Im stuck with the following problem and I hope you can help me. I have StopWordList.java where I define a String array as follows:
    Java Code:
    public static String stopWordList[] =  {"a", "about", ...}
    I created a hashmap and I display it (everything is ok = output is fine ) as follows:
    Java Code:
    public StopWordList(){
    	swlmap = new HashMap<String, Integer>();
    	createMap();
    	displayMap();
    }
    public void createMap(){
    	for (String s: stopWordList){
    	if ( swlmap.containsKey( s ) ) // is word in map
    	{
    	   int count = swlmap.get( s ); // get current count
    	   swlmap.put( s, count + 1 ); // increment count
    	} // end if
    	else
    	   swlmap.put( s, 1 );
    	}//end for 
    }//end menthod creatMap
    
    private void displayMap()
    {
       Set< String > keys = swlmap.keySet(); // get keys
       // sort keys
       TreeSet< String > sortedKeys = new TreeSet< String >( keys );
       System.out.println( "\n Map contains:\nKey\t\tValue" );
       // generate output for each key in map
       for ( String key : sortedKeys )
          System.out.printf( "%-10s%10s\n", key, swlmap.get( key ) );
       System.out.printf(
          "\nsize:%d\nisEmpty:%b\n", swlmap.size(), swlmap.isEmpty() );
    } // end method displayMap
    
    
    public static void main( String args[] )
    {
    	      new StopWordList();
    } // end main
    The problem is with my HashMapFiles.java file. Here I create another map:
    Java Code:
     public static void main(String[] args) {
            // Creating new HashMap objects
            // keys are String, values are Integer
            HashMap<String, Integer> wordcount = new HashMap<String, Integer>();
    for the words in a given .txt file (that is given also in this .java file). But what I want to do is : if a word in the .txt file is part of the array from the StopWordList.java ( is in the swlmap ) I DON'T want this word to be put in my wordcount map. What I did was to have an IF, like:
    Java Code:
    if (wordcount.containsKey(word) && swlmap.containsKey(word))
    but I get : slwmap cannot be resolved. I added
    Java Code:
    static HashMap<String, Integer> swlmap;
    as suggested by Eclipse and I get java.lang.NullPointerException error.

    I need this for a project and unfortunately I can't go on with this in the way.

    Thanks in advance

  2. #2
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,445
    Rep Power
    18

    Default

    Are these two different apps?
    You seem to have two main() methods...

  3. #3
    li_bi is offline Member
    Join Date
    Feb 2010
    Posts
    7
    Rep Power
    0

    Default

    Thanks for the reply. It's the same application. I deleted the main() from StopWordList.java and just call the methods with and object in HashMapFiles(). I still have the same errors as stated above.

  4. #4
    RamyaSivakanth's Avatar
    RamyaSivakanth is offline Senior Member
    Join Date
    Apr 2009
    Location
    Chennai
    Posts
    765
    Rep Power
    6

    Default

    Please post the code in codetag.

    try to print slwmap ...might be having null values
    Ramya:cool:

  5. #5
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,445
    Rep Power
    18

    Default

    Yep, as requested, post the code and the full stack trace of the exception (pointing out the line it's thrown from).

  6. #6
    li_bi is offline Member
    Join Date
    Feb 2010
    Posts
    7
    Rep Power
    0

    Default

    I did :
    Java Code:
    StopWordList ob2= new StopWordList();
            ob2.createMap();
            ob2.displayMap();
    and I kept only one condition in the if:
    Java Code:
     if (wordcount.containsKey(word))
    and everyhitng is fine.

    The problem with the java.lang.NullpointerException is when I add in my HasMapFiles.java this:
    Java Code:
    static HashMap<String, Integer> swlmap;
    and put in if (from above):
    Java Code:
    if (wordcount.containsKey(word)) && swlmap.containsKey(word))
    Thanks

  7. #7
    RamyaSivakanth's Avatar
    RamyaSivakanth is offline Senior Member
    Join Date
    Apr 2009
    Location
    Chennai
    Posts
    765
    Rep Power
    6

    Default

    still what u are asking is not clear.Just put the printstacktrace and trace the errpr line...might be HashMap itself is null
    Ramya:cool:

  8. #8
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,445
    Rep Power
    18

    Default

    Posting teeny tiny, disconnected bits of code really doesn't help.

    To me it looks like you haven't initialised your swlmap. Hence the NullPointer.

  9. #9
    li_bi is offline Member
    Join Date
    Feb 2010
    Posts
    7
    Rep Power
    0

    Default

    If I initialize my
    Java Code:
    swlmap
    map in HashMapFiles.java will that not be a problem? The map already has pairs. I am posting my 2 .java files:
    Java Code:
    public class StopWordList {
    	int total = 0;
    	private Map< String, Integer > swlmap;
    
    	public static String stopWordList[] =  {"a",''about"...}; //there are 450 words 
    public StopWordList(){
    	swlmap = new HashMap<String, Integer>();
    	createMap();
    	displayMap();
    }
    public void stopwl(){ //calculate the length of the stopWordList array
    		
    		for (int i = 0; i< stopWordList.length; i++){
    			total++; 
    		}// end for
    		System.out.printf("\nLength is: %d\n ", total);
    	
    	                    }//end method
    
    //create map 
    public void createMap(){
    	for (String s: stopWordList){
    	if ( swlmap.containsKey( s ) ) // is word in map
    	{
    	   int count = swlmap.get( s ); // get current count
    	   swlmap.put( s, count + 1 ); // increment count
    	} // end if
    	else
    	   swlmap.put( s, 1 );
    	}//end for 
    }//end menthod creatMap
    
    public void displayMap()
    {
       Set< String > keys = swlmap.keySet(); // get keys
       // sort keys
       TreeSet< String > sortedKeys = new TreeSet< String >( keys );
       System.out.println( "\n Map contains:\nKey\t\tValue" );
       // generate output for each key in map
       for ( String key : sortedKeys )
          System.out.printf( "%-10s%10s\n", key, swlmap.get( key ) );
       System.out.printf(
          "\nsize:%d\nisEmpty:%b\n", swlmap.size(), swlmap.isEmpty() );
    } // end method displayMap
    }
    My HashMapFiles.java looks like:
    Java Code:
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.HashMap;
     
    public class HashMapFiles {
    	
    	static HashMap<String, Integer> swlmap;
    	
        public static void main(String[] args) {
            // Creating new HashMap objects
            // keys are String, values are Integer
            HashMap<String, Integer> wordcount = new HashMap<String, Integer>();
            
            StopWordList ob2= new StopWordList();
            ob2.createMap();
            ob2.displayMap();
            
            try {
                // Opening file 
                BufferedReader in = new BufferedReader(new FileReader(
                        "/home/student/workspace/Reuters21578-Apte-90Cat/training/acq/0000722"));
                // string buffer for file reading  
                String str;
     
                // reading line by line from file   
                while ((str = in.readLine()) != null) {
                    str = str.toLowerCase(); // convert to lower case
     
                    // starting index, we'll use this to copy words from string
                    int idx1 = -1;
                    // process each characters 
                    for (int i = 0; i < str.length(); i++) {
                        // trigger condition if current character is not letter
                        // or it is the end of line 
                        if ( (!Character.isLetter(str.charAt(i))) || (i + 1 == str.length()) ) {
                            // do nothing if previous character was also non-letter
                            if (i - idx1 > 1) {
                                // copy word from input string buffer to new variable from previous non-letter  
                                // symbol to current symbol which is also non-letter
     
                                // if this is a letter(than it is last character in the line and we should    
                                // copy it to word)
                                if (Character.isLetter(str.charAt(i)))
                                    i++;
     
                                // copying 
                                String word = str.substring(idx1 + 1, i);
     
                                
    							// Check if word is in HashMap AND if it is a stopword
                                if (wordcount.containsKey(word)){ //&& swlmap.containsKey(word)) {
                                    // get number of occurrences for this word
                                    // increment it 
                                    // and put back again 
                                    wordcount.put(word, wordcount.get(word) + 1);
                                } else {
                                    // it means this is first time we see this word, set value '1'
                                    wordcount.put(word, 1);
                                }
                            }
     
                            // remember current position as last non-letter symbol                        
                            idx1 = i;
                        }
                    }
                }
                // Close buffered reader
                in.close();
            } catch (Exception e) {
                // If something unexpected happened 
                // print exception information and quit 
                e.printStackTrace();
                System.exit(1);
            }
     
            // This code sorts outputs HashMap sorting it by values
     
            // First we're getting values array 
            ArrayList<Integer> values = new ArrayList<Integer>();
            values.addAll(wordcount.values());
            // and sorting it (in reverse order)
            Collections.sort(values, Collections.reverseOrder());
     
            int last_i = -1;
            // Now, for each value 
            for (Integer i : values) {
                if (last_i == i) // without duplicates 
                    continue;
                last_i = i;
                // we print all hash keys 
                for (String s : wordcount.keySet()) {
                    if (wordcount.get(s) == i) // which have this value 
                        System.out.println(s + ":" + i);
                }
                // not elegant, but works 
            }
        }
    }
    I apologize for the looong code. Thank you

  10. #10
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,445
    Rep Power
    18

    Default

    Are you assuming the static swlmap in your HashMapFiles is the same as the one in StopWordList? They aren't. They may have the same name, but they aren't the same object.

  11. #11
    li_bi is offline Member
    Join Date
    Feb 2010
    Posts
    7
    Rep Power
    0

    Default

    Well, this is my first project/program where I use maps and the new concepts, so everything is kinda new. what should I change to make it work?

    Thanks

  12. #12
    li_bi is offline Member
    Join Date
    Feb 2010
    Posts
    7
    Rep Power
    0

    Default

    I did this

    Java Code:
    static StopWordList swlmap = new StopWordList();
    in my HashMapFiles.java and it works :). Thanks for the effort :).

    Have a great day

  13. #13
    Cbani is offline Member
    Join Date
    Jan 2010
    Posts
    90
    Rep Power
    0

    Default

    thats because your wordcount is not holding any element and the other map swlmap is also not holding any elements.

    you cant use any of the java objects which is defined in another .java in your .java

    Rather what you could do is to return the same map through a method call and then use that in your if() condition.

  14. #14
    li_bi is offline Member
    Join Date
    Feb 2010
    Posts
    7
    Rep Power
    0

    Default

    hello. thanks for the reply. So what I did earlier that made my program work is not actually using my swlmap properly in the HashMapFiles.java file?

    Thanks

Similar Threads

  1. Problems here
    By Keno777 in forum New To Java
    Replies: 2
    Last Post: 11-13-2009, 11:35 AM
  2. JAR problems
    By Evil Smurf in forum New To Java
    Replies: 4
    Last Post: 09-01-2009, 01:17 AM
  3. HashMaps get key for a specific value
    By andre1011 in forum Advanced Java
    Replies: 2
    Last Post: 03-11-2009, 02:30 AM
  4. having problems
    By pinkdiamondgail in forum New To Java
    Replies: 6
    Last Post: 02-06-2009, 11:35 PM
  5. many to many problems
    By cecily in forum JDBC
    Replies: 1
    Last Post: 08-02-2007, 05:51 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •