Gery
Gery

Reputation: 1

Default Values in a Hashmap

I have a problem which I can't solve. I want to solve Alphametics(e.g. SEND + MORE = MONEY --> O=0,M=1,Y=2,E=5,N=6,D=7,R=8,S=9) So I tried to make a Equation out of that like this: 1000*S+100*E+10*N+D + 1000*M+100*O+10*R+E = 10000*M+1000*O+100*N+10*E+Y So I tried to use a Hashmap, to collect this Data(this is just for the left side of the equation):

Scanner s = new Scanner(System.in);
        int HowMuchWords = s.nextInt();
        String[] Words = new String[HowMuchWords];
        for(int i = 0; i<Words.length;i++){
            Words[i] = s.next().toUpperCase();
        }
        HashMap<Character,Integer> Letters = new HashMap<Character, Integer>();

        for(int i = 0;i<Words.length;i++) {
            char[] LettersWord = Words[i].toCharArray();
            for (int j = 0; j < LettersWord.length; j++) {
                Letters.put(LettersWord[j],Letters.get(LettersWord[j])+(int) Math.pow(10, LettersWord.length - 1 - j));
       }

But I have problems with the Letters.get command. Because I want to add a number to null, the Value is still null. So I want to set the default value of every value in the Hashmap to 0. Is there a possibility to do that?

Upvotes: 0

Views: 5864

Answers (3)

nolexa
nolexa

Reputation: 2492

You can use an array instead of a Map. If you are just using ASCII, the range of characters maps to a range of indices. This code is also quicker to run, if performance matters in your case.

int[] Letters = new int['Z' - 'A' + 1];

...

// Inside the for loop
Letters[LettersWord[j] - 'A'] += (int) Math.pow(10, LettersWord.length - 1 - j);

Upvotes: 0

Jimmy
Jimmy

Reputation: 2619

You can override get(Object key) when you create your HashMap . Try this during Letters creation in your code, hope it helps.

 HashMap<Character,Integer> Letters = new HashMap<Character, Integer>(){
                @Override
                public Integer get(Object key) {
                    if(containsKey(key)){
                       return super.get(key);                          
                    }
                    return 0;
                }
            };

Upvotes: 1

chiastic-security
chiastic-security

Reputation: 20520

The easiest way by far is to write

Integer r = Letters.get(...);
if (r==null)
    r=0;

rather than mess about with arranging for your map to return a default value.

Or

int r = Letters.contains(...) ? Letters.get(...) : 0;

would also do it.

Upvotes: 1

Related Questions