Java Arrays - 搜索数组中的元素,然后查找索引

时间:2012-12-28 18:26:33

标签: java arrays

我正在尝试编写一个搜索城市的程序,给出一个邮政编码。该程序必须在数组邮政编码中搜索该邮政编码并返回该城市的名称。 我到目前为止的代码是:

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

我遇到的问题是我不知道如何将已被要求的代码链接到阵列中的城市。例如,用户输入代码2000,所以这是邮政编码[1],我想要的城市是安特卫普,因为城市[1]。

6 个答案:

答案 0 :(得分:4)

我会认真考虑使用HashMap代替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);

进一步适应您的任务:

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

编辑:阵列解决方案:

这是一个非常奇怪的方法,我必须说,但如果你真的想用数组做:

我假设城市数组的长度与邮政编码数组的长度相同。

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

答案 1 :(得分: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]);
}

答案 2 :(得分:2)

实际上,接受的答案将在每个查询中占用线性时间。虽然HashMap仍然是更好的选择(具有恒定的摊销时间),但如果重新排列它们,则可以比使用数组的线性时间更好,以便对postalCode进行排序。这允许您执行O(log(n))二进制搜索。

示例:

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

这导致了一个有趣的后续问题:如何以快速二进制搜索所需的方式对任意一组邮政编码和城市进行排序:

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

以下是rearrangeCities实施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;
} 

由于您的目标是提高您对Java中数组的了解,我相信这些都是很好的例子。

答案 3 :(得分:1)

当您在第一个数组中搜索时,保存成功的索引并获取另一个数组的元素。

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

现在你需要city[index]

应该在搜索循环之外声明

index,以便在搜索之后访问in(除非您以后不需要访问)

答案 4 :(得分:1)

由于您希望通过数组提高您的技能,我想这会有所帮助。没有什么复杂或有效但这已经足够了。

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

答案 5 :(得分:1)

使用两个数组确实不是这样做的方法,但是它显示的是city中与postalcode中相应索引的城市相同的城市{{1} }}

您需要通过postalcode进行线性搜索,然后拉出城市:

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

如果foundCity不为空,则您找到了拉链并拥有该城市。