Solved

Java arrays and/or dictionary pairing

Posted on 2012-03-15
22
202 Views
Last Modified: 2012-03-15
Hi,

I'm not a Java guy, but I wanted to work on a simple way to take some text files and convert them into objects that can be accessed as fast as possible, instead of having to iterate through an array with a foreach loop.

Attached is my list. I'd just like to get it to give me the name of the place that coincides with the zip code, as fast as possible.  I do Powershell so I would do a hash table.  So I'm assuming we'd be doing the same thing.

I've tried importing from a text file into a filestreamreader, but it wants it's own subroutine for it.  Again, I'm not savvy on Java, so I would love an example.

Any insight would be much appreciated.

DH
0
Comment
Question by:Dale Harris
  • 9
  • 9
  • 4
22 Comments
 
LVL 16

Author Comment

by:Dale Harris
ID: 37725357
I don't need this to be dynamic so should I just copy and paste it into my code?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37725614
Try

http://technojeeves.com/joomla/index.php/free/121-reading-a-file-into-a-list-of-string-in-java-7-and-above

You might need a more business domain object though, but you might start with the above
0
 
LVL 16

Author Comment

by:Dale Harris
ID: 37725698
CEHJ, thanks for the input.  Unfortunately it doesn't read it into a hash table, nor are you explaining the fastest way (if it is indeed a hashtable that is the fastest).  I found a bunch of pages and this one is a good one that I haven't seen yet, but putting it into the hashtable is the harder of the two things.

I am enjoying Google as much as the next person, but what I'm really looking for is a solid solution custom tailored to my issue (using my filenames, and variable names that match what I'm working with).  I consider myself to be fairly decent on a few programming languages, but Java is giving me a pretty difficult time.

For example, here's what I have so far:

Hashtable<String, Integer> ZipCodes
        = new Hashtable<String, Integer>();
      ZipCodes.put("one", 1);
      ZipCodes.put("two", 2);
      ZipCodes.put("three", 3);
      Enumeration enum1, enum2;
      enum1 = ZipCodes.keys();
      enum2 = ZipCodes.elements();

      String CityCode, CityName;
      while (enum1.hasMoreElements ())
      {
      CityCode = (String) enum1.nextElement();
      CityName = (String) enum2.nextElement();
      System.out.println("Zip Code " + CityCode + " Name " + CityName );

Open in new window


Even though nothing is popping up with an error in Eclipse,  it's still failing when I run it.

It might help if you guys knew I was doing it for android.

DH
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37725838
Can you post an example file?
0
 
LVL 16

Author Comment

by:Dale Harris
ID: 37726863
Sure.  Here's the Java file:
BAHCalculatorActivity.java
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37726877
I think this would make more sense:

package bahcalc.dbhtech.com;
import java.util.*;
import java.io.*;

import android.R.string;
import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BAHCalculatorActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
      //Hashtable<String, Integer> ZipCodes = LoadHashTableZipCodes();
		Hashtable<String, Integer> ZipCodes
        = new Hashtable<String, Integer>();
      ZipCodes.put("one", 1);
      ZipCodes.put("two", 2);
      ZipCodes.put("three", 3);
      Enumeration enum1, enum2;
      enum1 = ZipCodes.keys();
      enum2 = ZipCodes.elements();

      String CityCode, CityName;
      while (enum1.hasMoreElements ())
      {
      String CityName = (String) enum1.nextElement();

      int CityCode = ZipCodes.get(CityCode);
      System.out.println("Zip Code " + CityCode + " Name " + CityName );
      } 
    }

	//private Hashtable<String, Integer> LoadHashTableZipCodes() {

      //return ZipCodes;
	//}

}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37726887
So your Hashtable has CityName's of type String  as the keys a
and Zip codes as Integer as values.

So indeed you can use
Enumeration enum1 = ZipCodes.keys() to get the enumeration of the
keys- city names.
But the underlying types would be String, as you CityNmaes are Strings
Then you don't want the enumaration of vlaues,  as  there is no guarantee that they will go in the same order or anything like that.
In fact you want to go through all keys (city names) and for each key with the method get() of the Hahstable retrieve your CityCode
whioch will be either Integer object or they can be autoamtically unboxed into primitibve int's
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37726894
If you see any compilation error or execution excpetion - please, post the error and we'll try to address that
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37726909
Now I corrected mny code above which had many misprints and it now executes (I removed androind part as I don't have libarries for compilation):

import java.util.*;
import java.io.*;

//import android.R.string;
//import android.app.Activity;
//import android.os.Bundle;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BAHCalculatorActivity /*extends Activity */{
    /** Called when the activity is first created. */
  //  @Override
  //  public void onCreate(Bundle savedInstanceState) {
   //     super.onCreate(savedInstanceState);
    //    setContentView(R.layout.main);

        public static void main
        (String[]args){



      //Hashtable<String, Integer> ZipCodes = LoadHashTableZipCodes();
		Hashtable<String, Integer> ZipCodes
        = new Hashtable<String, Integer>();
      ZipCodes.put("one", 1);
      ZipCodes.put("two", 2);
      ZipCodes.put("three", 3);
      Enumeration enum1, enum2;
      enum1 = ZipCodes.keys();
      enum2 = ZipCodes.elements();

      String CityName;
        int CityCode;
      while (enum1.hasMoreElements ())
      {
       CityName = (String) enum1.nextElement();

      CityCode = ZipCodes.get(CityName);
      System.out.println("Zip Code " + CityCode + " Name " + CityName );
      }
    }

	//private Hashtable<String, Integer> LoadHashTableZipCodes() {

      //return ZipCodes;
	//}

}

Open in new window

Thsi is the output:
Zip Code 2 Name two
Zip Code 1 Name one
Zip Code 3 Name three

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 37726911
Mind that apart form two enumeartions issues in your origibal code which I mentioned above, another problem was that you declared CityCode as String, though your Hashtable was supposed to have valuesof type  Integer not String
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37726918
In general it is command practice in Java to have variables starting with lower case and class names starting with upper case.
So it is better to use cityName , cityCode - starting with lower case
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 16

Author Comment

by:Dale Harris
ID: 37726962
Ahh, thanks for that.  Can I twist this up a bit: I'd like to have the following data:
      ZipCodes.put(00501, "NY218");
      ZipCodes.put(00544, "NY218");
      ZipCodes.put(00601, "XX499");
      ZipCodes.put(31036, "GA076");
      ZipCodes.put(31037, "ZZ560");
      ZipCodes.put(31038, "ZZ740");

I have to do the lookup by zipcode, not viceversa.  So if that's the case, does that still work?  Remember, if we do a lookup by cityName, it will pull up multiple zip codes, but because there's only a single zipCode for fewer city names, we need to make sure the zipcode is our key as it's the only unique one.

Also, I've changed my code to have lower case for the first part of the variable.

DH
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37726977
Well if you want to revrese - mind of the types - if your zip codes are integers then you needd to decalre you Hastable as <Integer, String> not like it was before

In general as you are not going to add or mutiply zipcodes - i'd rather make zip codes also strings and have HashTable<String, String>
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 37726992
There you go with Hashtable<String, String>

and you are right keys should be unique

import java.util.*;
import java.io.*;

//import android.R.string;
//import android.app.Activity;
//import android.os.Bundle;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class BAHCalculatorActivity /*extends Activity */{
    /** Called when the activity is first created. */
  //  @Override
  //  public void onCreate(Bundle savedInstanceState) {
   //     super.onCreate(savedInstanceState);
    //    setContentView(R.layout.main);

        public static void main
        (String[]args){



      //Hashtable<String, Integer> ZipCodes = LoadHashTableZipCodes();
		Hashtable<String, String> ZipCodes
        = new Hashtable<String, String>();
    ZipCodes.put("00501", "NY218");
      ZipCodes.put("00544", "NY218");
      ZipCodes.put("00601", "XX499");
      ZipCodes.put("31036", "GA076");
      ZipCodes.put("31037", "ZZ560");
      ZipCodes.put("31038", "ZZ740");
      Enumeration enum1, enum2;
      enum1 = ZipCodes.keys();
     // enum2 = ZipCodes.elements();

      String cityName;
        String cityCode;
      while (enum1.hasMoreElements ())
      {
       cityCode = (String) enum1.nextElement();

      cityName = ZipCodes.get(cityCode);
      System.out.println("Zip Code " + cityCode + " Name " + cityName );
      }
    }

	//private Hashtable<String, Integer> LoadHashTableZipCodes() {

      //return ZipCodes;
	//}

}

Open in new window


Zip Code 00501 Name NY218
Zip Code 31038 Name ZZ740
Zip Code 31037 Name ZZ560
Zip Code 31036 Name GA076
Zip Code 00544 Name NY218
Zip Code 00601 Name XX499

Open in new window

0
 
LVL 16

Author Closing Comment

by:Dale Harris
ID: 37727064
Perfect.  I got my hashtable working and doing accurate lookups in it.  Now onto the next portion of my project.  Stay tuned!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37727085
I'm not a Java guy, but I wanted to work on a simple way to take some text files and convert them into objects that can be accessed as fast as possible

Sorry but the accepted answer just doesn't do that - are you aware of that?

Sure.  Here's the Java file:

I meant the text file that is the input
0
 
LVL 16

Author Comment

by:Dale Harris
ID: 37727103
CEHJ,

Yes I understand, but I wanted to make it as simple as possible and move from there.  I think adding the file dynamically to be read isn't needed.  I can hardcode the values for now.

Thanks for all the help in the beginning.  I'll be asking lots of dumb questions soon, so please stay tuned :)

DH
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 37727177
I think adding the file dynamically to be read isn't needed.  

Have to recompile your code, especially Android code, when you need to add/edit zip codes is a BAD idea ;)
0
 
LVL 16

Author Comment

by:Dale Harris
ID: 37727214
Granted, but it's good for a whole year :)  So in 2013, I will have to update it.  By that time, I hope to be much better at development.
0
 
LVL 16

Author Comment

by:Dale Harris
ID: 37727512
CEHJ, to prevent asking another question, can you tell me real quick how to create the variable within the package but in a different class, and then use that variable in my other class?

I've tried creating a class called ZipCodes

Then in there, I've defined ZipCodesList

But even after I import it in my code (import www.example.com.ZipCodes;) it still will not use ZipCodesList

What am I doing wrong?

This is one step away from putting it into a text file.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 37727514
SHow your code how you created variable and how you want to access it.
If it is static variable it should be accessible directly ZipCiodes.ZipCodesList

If it is intnace variable you need to pass it through method
0
 
LVL 16

Author Comment

by:Dale Harris
ID: 37727540
Here's the class:

public class ZipCodes {

	public static void main() {
		// TODO Auto-generated method stub
		Hashtable<String, String> ZipCodesList
        = new Hashtable<String, String>();
		ZipCodesList.put("00501", "NY218");
		ZipCodesList.put("00544", "NY218");
		ZipCodesList.put("00601", "XX499");
		ZipCodesList.put("31036", "GA076");
		ZipCodesList.put("31037", "ZZ560");
		ZipCodesList.put("31038", "ZZ740");
	      
	      //String ZipCode = ZipCodesList.get(query);
	      //return ZipCode;
	}

}

Open in new window


As you can see, I was trying to create a method to pass from my original class with

cityName = ZipCodes(cityCode);

So it would go to the class, and use it as an argument.  I had a line different though:
public static String main(String query) {

Open in new window

In my main class, I had the import, then I was calling it like you said:

cityName = ZipCodes.ZipCodesList.get(cityCode);

But it didn't like it.
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Fibonacci challenge 11 84
base64 decode encode 12 100
@SBGen Method 3 25
Java Timer (static) 9 19
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

743 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now