STheFox
STheFox

Reputation: 1498

Java Arrays - Searching an element in an array and then find the index

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].

Upvotes: 0

Views: 10108

Answers (6)

Anthony Accioly
Anthony Accioly

Reputation: 22461

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.

Upvotes: 2

Thousand
Thousand

Reputation: 6638

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])   

Upvotes: 4

Brian Roach
Brian Roach

Reputation: 76898

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.

Upvotes: 1

KyelJmD
KyelJmD

Reputation: 4732

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
         }
     }

Upvotes: 1

AFS
AFS

Reputation: 628

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)

Upvotes: 1

bellum
bellum

Reputation: 3710

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]);
}

Upvotes: 3

Related Questions