Search code examples
javahashmaptreemap

How to properly store to a hashmap and then copy over to a treemap to loop and display the key and values


I am storing user input into a hashmap then using it to build a Treemap from it to and then loop through and display key/values inside. Instead I only manage to store/display the 2 most recent user data entered.

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

public class Lab09 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int studentNbr = 0;
        int scoreNbr = 0;
        String name = "";

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


        System.out.println("How many students do you want to enter?");
        studentNbr = input.nextInt();
        input.nextLine();

        System.out.println("How many scores do you want to enter for each student?");
        scoreNbr = input.nextInt();
        input.nextLine();

        for(int i = 0; i < studentNbr; i++){
            System.out.println("Enter student number " + (i+1) + " name:");
            name = input.nextLine();
            int j = 0;
            while(j < scoreNbr){
                System.out.println("Enter score " + (j+1) + " for " + name + ":");
                students.put(name, input.nextInt());
                input.nextLine();
                j++;
            }

        }
        Map<String, Integer> sorted = new TreeMap<String, Integer>(students);
        for (String i : sorted.keySet()) {
            System.out.println("key: " + i + " value: " + sorted.get(i));
        }

    }
}

I expect to be able to display all key/values but instead only receive 2 lines displaying the most recent user input instead of all the data put in by the user.


Solution

  • HashMap in java will replace previous 'value' with new 'value' if 'key' is same. You can create composite key for 'students' map with student name and score id. e.g.

      students.put(name+'-'+j, input.nextInt());