How to use a counter inside a Hashmap?

Asked

Viewed 630 times

4

It is possible to do this?

public static void main(String[] args) {

    Scanner in = new Scanner (System.in);

    Map <String,Integer> mapa = new HashMap <String,Integer>();

    mapa.put("45 - Jose"  , ? ); //A "Key" deve ser o numero do Candidato,        
    mapa.put("13 - Maria" , ? ); // e  o "Value" o contador  que vai 
    mapa.put("20 - Pedro" , ? ); // contabilizar os votos,  porem nao sei
    mapa.put("50 - Carol" , ? ); // como criar  o contador aqui.      

    for (Map.Entry <String , Integer> conteudo : mapa.entrySet()){

        System.out.println(conteudo.getKey());

        System.out.printf("Votos = %d \n",conteudo.getValue());
    }

    String key, continuar;

    do{

    System.out.println("\nEm que candidato deseja votar? ");
    key =  in.nextLine();

    if (mapa.containsKey(key)){
        mapa.replace(key, new Integer (?));

        System.out.printf("\nCandidato: %s \nVotos = %d \n", key, mapa.get(key));  
    }else{
        System.err.printf("\nCandidato %s nao encontrado.\n" ,key);
    }

    System.out.println("\nDeseja continuar: (s/n)");
    continuar = in.nextLine();

    }while("s".equalsIgnoreCase(continuar));
  • Explain the difficulty you’re having, add a brief description of what you’ve done and what you’ve tried.

1 answer

4


To initialize the counter just put zero, as you would normally do. To increment you have to take the current value and already know that you do this with the method get() and to put the new value already knows that it is with put(), just need to join the two, obviously adding one to the found value before saving the new one, as always done on any counter. I mean, there’s nothing I couldn’t do.

import java.util.*;
class Ideone {
    public static void main(String[] args) {
        Scanner in = new Scanner (System.in);
        Map<String,Integer> mapa = new HashMap<String,Integer>();
        mapa.put("45 - Jose"  , 0); //A "Key" deve ser o numero do Candidato,        
        mapa.put("13 - Maria" , 0); // e  o "Value" o contador  que vai 
        mapa.put("20 - Pedro" , 0); // contabilizar os votos,  porem nao sei
        mapa.put("50 - Carol" , 0); // como criar  o contador aqui.      
        for (Map.Entry<String, Integer> conteudo : mapa.entrySet()) {
            System.out.println(conteudo.getKey());
            System.out.printf("Votos = %d \n", conteudo.getValue());
        }
        String continuar;
        do {
            System.out.println("\nEm que candidato deseja votar? ");
            String key =  in.nextLine();
            if (mapa.containsKey(key)) {
                mapa.put(key, mapa.get(key) + 1);
                System.out.printf("\nCandidato: %s \nVotos = %d \n", key, mapa.get(key));  
            } else {
                System.err.printf("\nCandidato %s nao encontrado.\n", key);
            }
            System.out.println("\nDeseja continuar: (s/n)");
            continuar = in.nextLine();
        } while ("s".equalsIgnoreCase(continuar));

    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

It would also be nice to maintain consistency in code organization.

  • It helped a lot was exactly what I needed, I wasn’t sure how to create the logic to implement (+1 from the counter), without creating a variable. I’m new to java programming only a few months, which means "It would also be nice to maintain consistency in code organization." I must change something?

  • 1

    The indentation, alignment, spacing, every hour you do one way. There is a reason to use each one of them deforms consistently. It is not embellishment, organize the code help to read it more easily and understand faster what is happening. For example avoid confusing functions with commands. Compare your code as mine looking specifically at spaces.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.