netbeans 当用户输入国际电话号码时获取国家a地区名称[重复]

juzqafwq  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(139)

此问题在此处已有答案

how to get country phone prefix from iso(4个答案)
去年关闭了。
所以我搜索了不同的库,但都没有找到。基本上,当用户输入电话号码时,我必须得到一个国家/地区的名称。如输出所示:+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());            
    }
yks3o0rb

yks3o0rb1#

我不知道这样的库是否存在,但你可以很快实现这样的东西。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()

相关问题