在 java 中将列表(用户输入)作为 HashMap 中的值

Putting a list(user input) as a value in HashMap in java

以下代码从用户那里获取分数并将其存储在分数列表中。我如何将此列表存储在 HashMap 中,其中每个列表应仅包含 2 个值。

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);
    }
}

您必须在循环中每次 re-initialize scores 列表。

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);
}