【问题标题】:how can I search the saved number如何搜索保存的号码
【发布时间】:2018-02-04 19:57:36
【问题描述】:

我想创建一个程序来保存国家代码并搜索国家代码。另外,保存国家代码的计数器最多有 20 个。我是一个新的java初学者。我想知道编写 searchCoutryCode 的正确方法是什么 以前用数组搜索保存的国家代码的方法?

public static void createCountryCode(String countryName, String countrycode) {  
    if (nameCounter >= 20) {                               
        System.out.println("Full");          
    } else {
        System.out.println("Saving the number of " + countryName + ":" + countryCode);           
    }   

    countryNameRec[countryNameCounter++] = countryName;                 
    countryCounterRec[countryCounter++]= countryCode;
}

public static void searchCoutryCode(String countryName) {
    for(int i = 0; i <=20; i++){
        if(countryNameRec[i].equals(countryName)){
            System.out.println("countryNameRec[i]+ " : "+ coutryCodeRec[i]");
        } else {
            System.out.println("No records"); 
        }
    }
}

【问题讨论】:

  • 之前保存的国家代码?在哪里?在文件或内存中?
  • 这也不编译,检查你的引号!
  • 正确的意思是高效吗?有许多正确的方法,但它们的效率可能不同。如果您存储在地图中,则查找速度很快。如果数组已排序,则查找速度会很快。如果数组是随机的,则查找最慢
  • 使用数组的内存

标签: java arrays boolean


【解决方案1】:

此代码假定国家/地区名称是唯一的。在您的代码中,您给出的消息是,列表大小已满,但无论如何都会添加记录。对于其他人推荐的这种问题,使用地图更合适。

public static HashMap<String,String> countries = new HashMap<>();

public static void createCountryCode(String countryName, String countrycode) {
    if (countries.size() >= 20) {
        System.out.println("Full");
    } else {
        System.out.println("Saving the number of " + countryName + ":" + countrycode);
        countries.put(countryName,countrycode);
    }
}

public static void searchCoutryCode(String countryName) {
    String countryCode = countries.get(countryName);
    if(countryCode == null){
        System.out.println("No records");
    }

    else{
        System.out.println("countryName+ " : "+ countryCode");
    }
}

【讨论】:

【解决方案2】:

在数组中迭代以查找元素并不是一种有效的方法。
好吧,因为你只有 20 个元素,它很可能不会引起真正的问题,但无论你以后可以有更多的元素来处理,而且这种做法不仅冗长。

使用带有排序数组的binarySearch (Arrays.binarySearch()) 或使用Map 可能会更好。

请注意,实际上您的 searchCoutryCode() 不会返回任何内容。 搜索方法必须返回一些东西:它找到的元素或什么都没有。 你可以返回String:

public static String searchCoutryCode(String countryName) {
   ...
}

或更好的Optional&lt;String&gt; 以更简洁的方式处理未找到的情况:

public static Optional<String> searchCoutryCode(String countryName) {
   ...
}

【讨论】:

    【解决方案3】:

    我建议您了解地图。它们是更智能的数组版本,并且就像字典一样,“键”就像单词,“值”就像定义。可以通过调用 java 库中的 containsValue() 或 containsKey() 方法来替换整个方法。

    但是,如果您想使用数组,我建议您查看作为 Java Arrays 库一部分的二进制搜索方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多