Exercise with HashMap

1

I'm trying to do this exercise, I do not know where I'm going wrong. Can you help me?

I need to create a map that has the key number of the characters in a city name and a value in a list with all names with that number of characters.

You need to make a print that lists the names of the cities and the number of characters that the names have. Try to have the code as few rows as possible.

How I did it. If you have suggestions for improvements ...

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class testeJava {

    public static void main(String[] args) {

        HashMap<Integer,String> hm=new HashMap<Integer,String>();

        Scanner nomeCidade = new Scanner(System.in);
        Scanner qtdCidade = new Scanner(System.in);

        System.out.println("Quantidade de Cidade a Adicionar?");
        int qtd = qtdCidade.nextInt();


        for (int i = 0; i < qtd; i++) {
            System.out.println("Informe Nome da Cidade?");
            String nome = nomeCidade.nextLine();
            hm.put(i,nome);

            for (int j = 0; j < nome.length(); j++) {
                if(hm.containsKey(nome.charAt(j))){
                //ESTA DANDO ERRO NESSA LINHA ABAIXO SOLICITANDO CAST.
                    hm.put(nome.charAt(j),hm.get(nome.charAt(j))+1); 
                } else {
                    hm.put(nome.charAt(j), 1);
                }
            }

        }

        for(Map.Entry m:hm.entrySet()){  
               System.out.println(m.getKey()+" "+m.getValue());  
        } 

        nomeCidade.close();
        qtdCidade.close();
    }
}
    
asked by anonymous 07.12.2017 / 19:25

1 answer

3

First, you should only use Scanner . Never use or create more than one and only new Scanner(System.in) . And there's no point in closing it.

Second, which class names should be uppercase. That is, use TesteJava instead of testeJava .

Third, as you yourself said, the values of Map should be a list of city names.

Fourth, blending nextInt() with nextLine() into Scanner brings unexpected and confusing results. See my other answer for an explanation.

Fifth, use the diamond syntax if possible.

Sixth, you'd rather declare variables whose types are abstractions rather than implementations. That is, avoid variables whose type is HashMap instead of Map .

Seventh, what you want to do is a lot easier if you use the compute(K, BiFunction<? super K, ? super V, ? extends V>) .

Eighth, avoid using types that are generic without generics.

Here is your patched code:

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class TesteJava {

    public static void main(String[] args) {

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

        Scanner scan = new Scanner(System.in);

        System.out.println("Quantidade de cidades a adicionar?");
        int qtd = Integer.parseInt(scan.nextLine());

        for (int i = 0; i < qtd; i++) {
            System.out.println("Nome da " + (i + 1) + "a cidade?");
            String nome = scan.nextLine();
            map.compute(nome.length(), (k, v) -> {
                List<String> nomes = v != null ? v : new ArrayList<>();
                nomes.add(nome);
                return nomes;
            });
        }

        for (Map.Entry<Integer, List<String>> entry : map.entrySet()) {  
            System.out.println(entry.getKey() + " " + entry.getValue());  
        } 
    }
}

If this entry is given for this code:

21
Bauru
Poá
Londrina
Franca
Itapevi
Osasco
Salvador
Suzano
São Paulo
Vitória
Cuiabá
Maceió
Belém
Curitiba
Macapá
Rio Branco
Manaus
Belo Horizonte
Recife
Itu
Rio de Janeiro

This will be the output produced at the end:

3 [Poá, Itu]
5 [Bauru, Belém]
6 [Franca, Osasco, Suzano, Cuiabá, Maceió, Macapá, Manaus, Recife]
7 [Itapevi, Vitória]
8 [Londrina, Salvador, Curitiba]
9 [São Paulo]
10 [Rio Branco]
14 [Belo Horizonte, Rio de Janeiro]

See here working on ideone.

    
07.12.2017 / 19:52