0

I am trying to write a program for searching a city, given a postal code. The program has to search that postal code in the array postalcode and give the name of the city back. The code I have so far is:

.

import javax.swing.JOptionPane;

public class Postalcode 
{

    public static void main(String[] args) 
    {
        int[] postalcode = {9300,2000,1000,9200,9000,8500,9700,2300};
        String[] city = {"Aalst","Antwerpen","Brussel","Dendermonde","Gent","Kortrijk","Oudenaarde","Turnhout"};

        int code = Integer.parseInt(JOptionPane.showInputDialog("Give a postal code")); 
    }
}

The problem I am having is that I don't know how to link the code that's been asked to a city in the array. For exemple, the user types as code 2000, so that's postalcode[1], the city I want is Antwerpen because city[1].

4
  • 11
    You would be far better served with a Map<Integer, String>. Commented Dec 28, 2012 at 18:29
  • are you open for alternatives other than arrays? in your case, a map will be good data structure on your given scenario Commented Dec 28, 2012 at 18:29
  • I haven't worked with maps before, I am trying to improve my knowledge of arrays in java. So I want to do this program with arrays Commented Dec 28, 2012 at 18:31
  • Use the correct data structure for the problem at hand Commented Dec 28, 2012 at 21:26

6 Answers 6

4

I would seriously consider using a HashMap for this instead of 2 Arrays.

HashMap<int,String> cities =  new HashMap<int,String>();
cities.put(9000,"Gent");
cities.put(9400,"Aalst"); 
String city = cities.get(9400);
System.out.println(city);

To further adapt to your assignment:

 int code = Integer.parseInt(JOptionPane.showInputDialog("Give a postal code"));
 string city = cities.get(code);

EDIT: Solution for Arrays:

This is a very weird approach I must say but if you really want to do it with arrays:

I'm assuming that the length of the city array is the same as the length of the postalcode array.

   int index = 0;
   int pCode = 9300;

for (int i = 0; i < postalcode.length; i ++)
{                       
  if (pCode == postalcode[i])
     {
        index = i;
        break;
     }

 }   

System.out.println(cities[index])   
Sign up to request clarification or add additional context in comments.

2 Comments

I don't want to work with maps, I want to improve my knowledge of arrays. So this will be a challenge for me without you.
@user1873613 : its upto you what you want to use or learn. As for the answer it doesn't deserve a downvote
3
int code = Integer.parseInt(JOptionPane.showInputDialog("Give a postal code"));

int requiredIndex = -1;
for (int i = 0; i < postalcode.length; i++)
    if (postalcode[i] == code)
        requiredIndex = i;
if (requiredIndex == -1){
    //there is no such postal code
} else {
    //your city is
    System.out.println(city[requiredIndex]);
}

1 Comment

This works, thanks a lot. It isn't that difficult, I should be able to have figured it out myself dough.
2

Actually, the accepted answer will take linear time per query. While a HashMap is still a better option (with constant amortized time), you can do better than linear time with arrays if you rearrange them so that postalCode is sorted. This allow you to perform O(log(n)) binary searches.

Example:

final int[] orderedPostCode = { 1000, 2000, 2300, 8500, 9000, 9200, 9300, 9700 };
final String[] orderedCities = { "Brussel", "Antwerpen", "Turnhout", "Kortrijk", "Gent", "Dendermonde", "Aalst", "Oudenaarde" };

final int code = Integer.parseInt(JOptionPane.showInputDialog("Give a postal code"));

final int codePos = Arrays.binarySearch(orderedPostCode, code);
if (codePos < 0) {
    JOptionPane.showMessageDialog(null, "Postal code not found", "Error", JOptionPane.ERROR_MESSAGE);
}
else {
    JOptionPane.showMessageDialog(null, "City: " + orderedCities[codePos]);
} 

This leads to a interesting follow up problem: How to sort an arbitrary set of postal codes and cities in the way needed for fast binary searches:

int[] postalCode = {9300,2000,1000,9200,9000,8500,9700,2300};
String[] city = {"Aalst","Antwerpen","Brussel","Dendermonde","Gent","Kortrijk","Oudenaarde","Turnhout"};

int[] orderedPostCode = Arrays.copyOf(postalCode, postalCode.length);
Arrays.sort(orderedPostCode);
String[] orderedCities = rearrangeCities(city, postalCode, orderedPostCode);
System.out.println(Arrays.toString(orderedPostCode));
System.out.println(Arrays.toString(orderedCities));
// Will print the arrays of the first example

And here is the rearrangeCities implementation O(n²):

private static String[] rearrangeCities(String[] cities, int[] postalCode, int[] orderedPostCode) {
    final String[] orderedCities = new String[cities.length];
    for (int newPos = 0; newPos < orderedPostCode.length; newPos++) {
        final int curPostalCode = orderedPostCode[newPos];
        for (int oldPos = 0; oldPos < postalCode.length; oldPos++) {
            if (postalCode[oldPos] == curPostalCode) {
                orderedCities[newPos] = cities[oldPos];
                break;
            }
        }
    }
    return orderedCities;
} 

Since your goal is to improve your knowledge of arrays in Java, I believe that these are good examples.

Comments

1

When you search in the first array save the successful index and get that element of the other array.

    if(postalCode[i]==input)
        index=i;

and now you want city[index]

index should be declared outside of the searching for loop so that in can be accessed after the search(unless you won't need later access)

Comments

1

Since you want to improve your skills with arrays I guess this will help. nothing complex or efficient but this is enough.

 int[] postalcode = {9300,2000,1000,9200,9000,8500,9700,2300};
     String[] city = {"Aalst","Antwerpen","Brussel","Dendermonde","Gent","Kortrijk","Oudenaarde","Turnhout"};

     int code = Integer.parseInt(JOptionPane.showInputDialog("Give a postal code")); 

     for(int i = 0; i< postalcode.length;i++){
         if(postalcode[i] == code){
          System.out.println(city[i]); 
              //or do something with the value here
         }
     }

Comments

1

Using two arrays really isn't the way to do this, but it appears what you have is the city at the same index in city as the corresponding code in postalcode

You would need to do a linear search through postalcode then pull the city:

String foundCity = null;
for (int i = 0; i < postalcode.length; i++)
{
    if (postalcode[i] == code)
    {
        foundCity = city[i]; 
        break;   
    }
}

If foundCity is not null, you found the zip and have the city.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.