How to find the country code by the country name in Java

1 Answer

0 votes
import java.util.Scanner;

public class CountryCodeLookup {

    // -------------------------------------------------------------
    // normalizeCountryName
    // Converts "france", "FRANCE", "fRaNcE" → "France"
    // Converts "united states" → "United States"
    // This matches the format used in the map keys.
    // -------------------------------------------------------------
    public static String normalizeCountryName(String s) {
        // Convert entire string to lowercase first
        s = s.toLowerCase();

        // Capitalize the first letter of each word
        StringBuilder result = new StringBuilder(s.length());
        boolean capitalizeNext = true;

        for (char c : s.toCharArray()) {
            if (capitalizeNext && Character.isLetter(c)) {
                result.append(Character.toUpperCase(c));
                capitalizeNext = false;
            } else {
                result.append(c);
            }

            if (c == ' ') {
                capitalizeNext = true;
            }
        }

        return result.toString();
    }

    // -------------------------------------------------------------
    // getCountryCode
    // Works with lowercase, uppercase, mixed-case input.
    // Map stays exactly as you defined it.
    // -------------------------------------------------------------
    public static String getCountryCode(String countryName) {

        // Lookup table stored exactly as given
        String[][] countryCodes = {
            {"United States", "US"},
            {"Canada", "CA"},
            {"United Kingdom", "GB"},
            {"France", "FR"},
            {"Germany", "DE"},
            {"Romania", "RO"},
            {"Japan", "JP"},
            {"Australia", "AU"},
            {"Hungary", "HU"}
        };

        // Normalize input to match map keys
        String key = normalizeCountryName(countryName);

        // Search the array
        for (String[] entry : countryCodes) {
            if (entry[0].equals(key)) {
                return entry[1];
            }
        }

        return "Unknown";
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a country name: ");
        String name = scanner.nextLine();

        String code = getCountryCode(name);

        System.out.println("Country code: " + code);

        scanner.close();
    }
}


/*
run:

Enter a country name: japan
Country code: JP

*/

 



answered 5 days ago by avibootz

Related questions

...