Skip to content
Advertisement

adding strings (key) to a Map where the value is the length of each String

Need to add 4 Strings – as a keys, using scanner, to a Map and the value has to be the lenght of each String.

for example: “House” – 5 etc .

Scanner sc = new Scanner(System.in);

    Map<String, Integer> linkedMap1 = new LinkedHashMap<>();

    for (int i = 0; i < 4; i++) {
        linkedMap1.put(sc.next(), sc.next().length());
        System.out.println(linkedMap1);
    }

Advertisement

Answer

You’r calling the scanner twice, so that’s 2 input as you need only one per word

String word;
for (int i = 0; i < 4; i++) {
    word = sc.nextLine();
    linkedMap1.put(word, word.length());
}
System.out.println(linkedMap1);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement