mardi 15 août 2023

HashMap extending to random length instead of 7 with for loop

I have two arrays for a card game one of type and another of color in Java. I want to run a for loop of length 7 to assert random values to the HashMaps which would be the card list for each player. But though I run the loop 7 times some Lists fill upto 5 while some upto 6. Here's the code:

static HashMap<String, String> p1=new HashMap<>(),p2=new HashMap<>(),p3=new HashMap<>(),u=new HashMap<>();
    
    public static void ini(){
        String [] colors = {"red", "green", "blue", "yellow"};
        String [] type = {"1","2","3","4","5","6","7","8","9","+2","+4","w","r"};
        Random r = new Random();
        for (int i = 0; i < 7; i++){
            p1.put(type[r.nextInt(type.length-1)],colors[r.nextInt(colors.length-1)]);
            p2.put(type[r.nextInt(type.length-1)],colors[r.nextInt(colors.length-1)]);
            p3.put(type[r.nextInt(type.length-1)],colors[r.nextInt(colors.length-1)]);
            u.put(type[r.nextInt(type.length-1)],colors[r.nextInt(colors.length-1)]);
        }           
    }
public static void main(String[] args){
        ini();
        System.out.println(p1);
        System.out.println(p2);
        System.out.println(p3);
        System.out.println(u);
    }

Any help would be grateful!

Expectation : 7 elements / List Outcome: 4 or 5 / List




Aucun commentaire:

Enregistrer un commentaire