Converting map.get(char) into an integer

Asked by At

I am learning java and am building a program that will count the times a letter occurs in a string. For some reason I cannot get an integer value from a map without having (int) in front. Can someone please explain this to me?

    Scanner scanner = new Scanner(System.in);
    String string = scanner.nextLine();
    LinkedHashMap map = new LinkedHashMap();


    for (char Char1: string.toCharArray()) {
        char Char = Character.toLowerCase(Char1);
        System.out.println(Char);

        if (map.containsKey(Char)) {
            int value = (int) map.get(Char);
            map.put(Char, value + 1);
        }
        else {
            map.put(Char, 1);
        }

    }

    System.out.print(map);
}

I am expecting "int value = map.get(Char)" to already store an integer value in the variable "value", but this isn't happening without putting (int) in from of the line of code. If I don't include the (int), i get "Type Mismatch: cannot convert from Object to int"

0 Answers