0

So I have searched for different libraries and couldn't find them. Basically, I have to get a country name when a user entered a phone number. Like the output shows: +1 (United States) +92(Pakistan) + 93(Afghanistan)

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

1 Answers1

0

I do not know if such a library exists, but you can implement something like this pretty quickly. Here you can find a JSON form of all International codes and Country Names. You could read this through your java program and transform it into an array with objects or into a more suitable way, a HashMap<String, String> and access them directly. Or fill your HashMap manually.

A small example would be:

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

If you will have your phone numbers with a specific format, for example, they would always have spaces as separators e.g. +1 123.., then you could eliminate the forEach and use .get() directly.

Renis1235
  • 4,116
  • 3
  • 15
  • 27
  • If I am using java on NetBeans where should i use JSON code in? – Abdul Haseeb Oct 11 '21 at 07:02
  • You could use a `JSON` library to read them. Check my answer here for more info: https://stackoverflow.com/a/69491628/7954021. You could also just fill the Map yourself If you do not know/ do not want to spend time on reading JSON Props. – Renis1235 Oct 11 '21 at 07:09