【问题标题】:Get a Country Name when user entered an international phone number [duplicate]当用户输入国际电话号码时获取国家名称[重复]
【发布时间】:2021-11-29 22:26:48
【问题描述】:

所以我搜索了不同的库但找不到它们。 基本上,当用户输入电话号码时,我必须得到一个国家名称。 如输出所示:+1(美国)+92(巴基斯坦)+93(阿富汗)

      public static void main(String[] args) throws NumberParseException {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter your phone no.:");
      String phone = sc.next();
    PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
    try{
        Phonenumber.PhoneNumber locale = phoneUtil.parse(phone, "");
        System.out.println("Country code: " + locale.getCountryCode()   );
        

    }
    catch(NumberParseException e){
        System.err.println("NumberParseException was thrown: " + e.toString());            
    }

【问题讨论】:

  • 查看可用于完成工作的多个库的副本。

标签: java netbeans libraries


【解决方案1】:

我不知道这样的库是否存在,但你可以很快地实现这样的东西。 Here 你可以找到所有国际代码和国家名称的 JSON 格式。您可以通过您的 java 程序读取它并将其转换为包含对象的数组或更合适的方式,HashMap<String, String> 并直接访问它们。或者手动填写您的HashMap

一个小例子是:

String phoneNr = "+355 69 55 79 418"
HashMap<String, String> prefixCountryMap = getPrefixCountryMap(); // This would be your function to get the HashMap, the values should be like this [ "+355" -> "Albania", "+1" -> "United States" ...]

// getting the Country name through the Prefix:
prefixCountryMap.forEach((key, value) ->
{
    if(phoneNr.startsWith(key))
    {
        return value; // This should be the country
    }
});

如果您的电话号码具有特定格式,例如,它们将始终使用空格作为分隔符,例如+1 123..,那么你可以去掉forEach,直接使用.get()

【讨论】:

  • 如果我在 NetBeans 上使用 java,我应该在哪里使用 JSON 代码?
  • 您可以使用JSON 库来阅读它们。在此处查看我的答案以获取更多信息:stackoverflow.com/a/69491628/7954021。如果您不知道/不想花时间阅读 JSON Props,您也可以自己填写地图。
猜你喜欢
  • 2021-08-24
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
  • 2015-01-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多