Home > Software engineering >  Putting a list(user input) as a value in HashMap in java
Putting a list(user input) as a value in HashMap in java

Time:05-07

The following code get score from the user and stores it in scores list. How can i store this list in a HashMap, where each list should hold only 2 values.

final int TOTAL_NO_OF_MATCHES = 2;
final int TOTAL_NO_OF_PLAYERS = 2;
List<Integer> scores = new ArrayList<>(); 
LinkedHashMap<String, List<Integer>> batsmanScores = new LinkedHashMap<>();
// LinkedHashMap<String, Integer> match2 = new LinkedHashMap<>();
// LinkedHashMap<String, Integer> match3 = new LinkedHashMap<>();
// LinkedHashMap<String, Integer> match4 = new LinkedHashMap<>();
// LinkedHashMap<String, Integer> match5 = new LinkedHashMap<>();

void storingScores()
{
    String batsmanName;
    for(int player = 1; player <= TOTAL_NO_OF_PLAYERS; player  )
    {
        System.out.println("Enter the Batsman" player "'s data: ");
        System.out.println("Enter the batsman's name: ");
        batsmanName = scan.nextLine();
        for(int match = 1; match <= TOTAL_NO_OF_MATCHES; match  )
        {
            System.out.println("Enter the score of Match" match ": ");
            int score = scan.nextInt();           
            scores.add(score);
        }
        scan.nextLine();
        batsmanScores.put(batsmanName, scores);
    }
}

CodePudding user response:

You have to re-initialize the scores list each time in the loop.

for(int player = 1; player <= TOTAL_NO_OF_PLAYERS; player  )
{
    System.out.println("Enter the Batsman" player "'s data: ");
    System.out.println("Enter the batsman's name: ");
    batsmanName = scan.nextLine();
    scores = new ArrayList<>(); //create new scores list

    for(int match = 1; match <= TOTAL_NO_OF_MATCHES; match  )
    {
        System.out.println("Enter the score of Match" match ": ");
        int score = scan.nextInt();           
        scores.add(score);
    }
    scan.nextLine();
    batsmanScores.put(batsmanName, scores);
}
  • Related