amveg
amveg

Reputation: 1

What is my error in a map in Java?

I am trying to solve this problem: http://www.cstutoringcenter.com/problems/problems.php?id=4, but I cant figure out why my code doesnt solve this, I mean in the "for" how can I can multiply the letters? What is my error? It just tell always 7, but I want to multiple all the letters. I hope you can help me.

public class ejercicio3 {

    public static void main(String args[]) {

        Map<Character, Integer> telefono = new HashMap<Character, Integer>();

        telefono.put('A', 2);
        telefono.put('B', 2);
        telefono.put('C', 2);
        telefono.put('D', 3);
        telefono.put('E', 3);
        telefono.put('F', 3);
        telefono.put('G', 4);
        telefono.put('H', 4);
        telefono.put('I', 4);
        telefono.put('J', 5);
        telefono.put('K', 5);
        telefono.put('L', 5);
        telefono.put('M', 6);
        telefono.put('N', 6);
        telefono.put('O', 6);
        telefono.put('P', 7);
        telefono.put('R', 7);
        telefono.put('S', 7);
        telefono.put('T', 8);
        telefono.put('U', 8);
        telefono.put('V', 8);
        telefono.put('W', 9);
        telefono.put('X', 9);
        telefono.put('Y', 9);

        String mensaje = "Practice";
        int producto = 1;

        for (char c : mensaje.toCharArray()) {    
            if (telefono.containsKey(c)) {
                producto = telefono.get(c) * producto;
                System.out.println(producto);
            }
        }
    }
}

Upvotes: 0

Views: 151

Answers (3)

Jonik
Jonik

Reputation: 81761

After fixing the case-sensitivity problem as suggested in Adrian Mouat's answer, the problem remains that with longer strings the integer overflows pretty soon. Use long instead:

long producto = 1;

(After that e.g. "Programming Challenges are fun" produces 208129028102553600.)

Edit: Or, as WineSoaked correctly points out, use BigInteger to make this support arbitrarily long strings (only the RAM available to JVM is then the limit). But, as we've seen, long was good enough for this particular puzzle. :-)

Upvotes: 2

WineSoaked
WineSoaked

Reputation: 1485

Looks like a case sensitivity issue. That is, "P" is the only character actually found in the map.

If you want to use a mixed-case string, either do mensaje.toUpperCase().toCharArray() or add lower case equivalent letters to the map, like telefono.put('a',2);

Upvotes: 1

Adrian Mouat
Adrian Mouat

Reputation: 46500

Convert your string to all uppercase first!

It's only finding the first character, 'P', for which it gives the correct answer of 7.

Try changing:

for (char c : mensaje.toCharArray()) {

to

for (char c : mensaje.toUpperCase().toCharArray()) {

Upvotes: 4

Related Questions