Solved

Assigning HashMap to HashMap.

Posted on 2004-08-31
16
1,656 Views
Last Modified: 2008-03-10
Hello Everybody,

I have a program which will parse the  input file into Key values pair and return the HashMap.
This programme is working fine. I can print out the key/value pairs. Problem is when in main method I assign this HashMap to new HashMap the values are gone.

public Static void main( String args[]) {

HashMap hm = new HashMap;

hm = parse("filename");

System.out.println(hm.get("UserID");
}

public HashMap parse(File file) {

HashMap h = new HashMap();

// parsing and putting key/values into hash

return h;
}

UserID is one of the Key...I can print out from the parse program correctly.
But from main I receive value "null"
What could be the problem?

Thanks,
Kedlu
0
Comment
Question by:kedlunanu
[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
  • 6
  • 5
  • 2
  • +3
16 Comments
 
LVL 92

Expert Comment

by:objects
ID: 11948117
public Static void main( String args[]) {

HashMap hm = parse(new File("filename"));

System.out.println(hm.get("UserID");
}

public static HashMap parse(File file) {

HashMap h = new HashMap();

// parsing and putting key/values into hash

return h;
}
0
 
LVL 6

Expert Comment

by:expertmb
ID: 11948610
can you post the code.
some where in the code hashmap might be getting reset.
0
 
LVL 16

Expert Comment

by:gnoon
ID: 11949120
>I can print out from the parse program correctly
Which part of the function you printed it out?

To dubug this problem, I think you should try to print it out at the end of 'parse' function before the return statement.
For example,

public static HashMap parse(File file) {
  HashMap h = new HashMap();

  // parsing and putting key/values into hash

  System.out.println(h.get("UserID");
  return h;
}

If the result still be null, so the problem should be in the parsing and putting section of the 'parse' function.
0
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 
LVL 1

Expert Comment

by:talvio
ID: 11949547
Hi,

hmm, your code has quite a few typos in it, but after correcting those it does work:
public static void main( String args[]) {
    HashMap hm = new HashMap();
    hm = parse("filename");
    System.out.println(hm.get("UserID"));
}
public static HashMap parse(String str) {
    HashMap h = new HashMap();
//     parsing and putting key/values into hash
    h.put("UserID", "Yo!");  // <-- added to test the function
    return h;
}

But as noted by objects you should get rid the first HashMap creation as it is totally unnecessary.

I'd encourage you to look at java.util.Properties -class. That would seem to fit to your problem.
Properties is a hashmap like (actually extends HashTable), but it stores only Strings. This is quite
usefull as you are using Strings in your hashmap. This would free you from unnecessary casting
you need to do al the time with HashMap. Also Properties offers some very usefull methods such as:
- void load(InputStream inStream) parses your file for you, if the format is suitable for you
- String getProperty(String key, String defaultValue) lets you set a default value if no value is found.

Look at the javadoc of java.util.Properties, it should ease your work.

br,
-jT
0
 

Author Comment

by:kedlunanu
ID: 11955622
public HashMap parse(File file) {
            
            String line;
            StringTokenizer st ;
            HashMap hm = new HashMap();
            String s;
            String s1;      
                  
            try{
                  
            BufferedReader in = new BufferedReader(new FileReader(file));
                  while ((line=in.readLine()) != null){
                        st = new StringTokenizer(line,"=");
                        s = st.nextToken();
                        s1= st.nextToken();
                                              hm.put(s,s1);
                              
                        }
                        
                  }catch(IOException e) {
                        
                        System.out.println("IOException" + e);
                  }
            
              System.out.println(hm.get("UserID"));
                                  return hm;
            
      }

public static void main (String args[]) {

HashMap hmt = parseConfigFile("config.txt");
System.out.println(hmt.get("UserID"));
      }

I can't print out "UserID" from main method or parse method. I was printing tokens and they were getting printed correct.

Please see what is the problem in the program.
Thanks
0
 
LVL 35

Expert Comment

by:girionis
ID: 11955799
> I can't print out "UserID" from main method or parse method.

Are you sure the "UserID" (check for case sensitivity) exists as a key?
0
 

Author Comment

by:kedlunanu
ID: 11955937
Yes...I'm printing out other fields too...but they are returning 'null' value.
I guess this is the problme of scope? becasue after I insert values inside the hash, if immediately after that I print out...they are printing out correct.

 Comment from objects  feedback
Date: 08/31/2004 05:41PM PDT
 Comment  


public Static void main( String args[]) {

HashMap hm = parse(new File("filename"));

System.out.println(hm.get("UserID");
}

public static HashMap parse(File file) {

HashMap h = new HashMap();

// parsing and putting key/values into hash

return h;
}

 
Comment from expertmb  feedback
Date: 08/31/2004 08:17PM PDT
 Comment  


can you post the code.
some where in the code hashmap might be getting reset.
 
Comment from gnoon  feedback
Date: 08/31/2004 09:59PM PDT
 Comment  


>I can print out from the parse program correctly
Which part of the function you printed it out?

To dubug this problem, I think you should try to print it out at the end of 'parse' function before the return statement.
For example,

public static HashMap parse(File file) {
  HashMap h = new HashMap();

  // parsing and putting key/values into hash

  System.out.println(h.get("UserID");
  return h;
}

If the result still be null, so the problem should be in the parsing and putting section of the 'parse' function.
 
Comment from talvio  feedback
Date: 08/31/2004 11:31PM PDT
 Comment  


Hi,

hmm, your code has quite a few typos in it, but after correcting those it does work:
public static void main( String args[]) {
    HashMap hm = new HashMap();
    hm = parse("filename");
    System.out.println(hm.get("UserID"));
}
public static HashMap parse(String str) {
    HashMap h = new HashMap();
//     parsing and putting key/values into hash
    h.put("UserID", "Yo!");  // <-- added to test the function
    return h;
}

But as noted by objects you should get rid the first HashMap creation as it is totally unnecessary.

I'd encourage you to look at java.util.Properties -class. That would seem to fit to your problem.
Properties is a hashmap like (actually extends HashTable), but it stores only Strings. This is quite
usefull as you are using Strings in your hashmap. This would free you from unnecessary casting
you need to do al the time with HashMap. Also Properties offers some very usefull methods such as:
- void load(InputStream inStream) parses your file for you, if the format is suitable for you
- String getProperty(String key, String defaultValue) lets you set a default value if no value is found.

Look at the javadoc of java.util.Properties, it should ease your work.

br,
-jT

 
Comment from kedlunanu
Date: 09/01/2004 10:33AM PDT
 Your Comment  


public HashMap parse(File file) {
         
          String line;
          StringTokenizer st ;
          HashMap hm = new HashMap();
          String s;
          String s1;    
               
          try{
               
          BufferedReader in = new BufferedReader(new FileReader(file));
               while ((line=in.readLine()) != null){
                    st = new StringTokenizer(line,"=");
                    s = st.nextToken();
                    s1= st.nextToken();
                    hm.put(s,s1);

                   /*********    printing out immediately ***************/

                    System.out.ptintln(hm.get(s).toString());
                         
                   /*******************************************/
                    }
                   
               }catch(IOException e) {
                   
                    System.out.println("IOException" + e);
               }
         
            System.out.println(hm.get("UserID"));
                                  return hm;
         
     }
 
 
0
 
LVL 35

Expert Comment

by:girionis
ID: 11956022
It's not matter of scope since you are returning the HashMap. So do you see the UserID inside the creation method but not outside (in the main)?
0
 

Author Comment

by:kedlunanu
ID: 11956083
I see UserID immediately after I put the entries in the HashMap but not just before I'm returning the HashMap...is weird
0
 
LVL 35

Expert Comment

by:girionis
ID: 11956579
What is the value os the "s" here:

System.out.ptintln(hm.get(s).toString());

What happens if you do

System.out.println("s: " + s);
0
 

Author Comment

by:kedlunanu
ID: 11956626
This is the output for your porgram:

s: IsLocal      
s: MachineName
s: UserID
s: Password
s: Database
s: DatabaseAlias
s: SchemaName


So the fields are printing out correctly.
I dont know what could be the problem.
0
 
LVL 35

Accepted Solution

by:
girionis earned 50 total points
ID: 11957775
There might be some space in front after the key. What happens if you do this:

 hm.put(s.trim(),s1);

Do you still have the same problem?
0
 
LVL 92

Expert Comment

by:objects
ID: 11958463
What is the output from the code you are using?
0
 

Author Comment

by:kedlunanu
ID: 11958505
This file is a profile...I need to parse this file and use values of the parameter in the program.
Username,password,database based on this value program will run. Automating our product.
0
 

Author Comment

by:kedlunanu
ID: 11958564
Hey girionis...
It worked with trim().
It was indeed considering some space after each word and so was not able to recognize the key.
Thanks so much for your valueable suggestions.
Kedlu
0
 
LVL 35

Expert Comment

by:girionis
ID: 11960800
:)
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
How to get all the API from website? 11 161
Need Help! Getting a syntax error and don't understand why 3 56
Java List 4 76
Eclipse neon2 "Java build path" correctness 7 44
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 how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Suggested Courses

752 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