1

How do I get the code below to repeat the command, where the players name already exists in the key set?

public static Map<String, Player> players = new TreeMap<>();

 for (int loop = 1; loop <= 4; loop++) {
        
        System.out.println("enter player"+loop+"s name");
        name = scanner.next();
        if(players.keySet().contains(name)) {
            System.out.println("name in use - enter new name");
        }else {
            players.put(name, new Player());
        }
        
        
    }

2 Answers 2

1

You can use a variable (e.g. boolean alreadyExists as shown in the code below) to track a valid input and loop back in case of invlid input.

boolean alreadyExists;

for (int loop = 1; loop <= 4; loop++) {
    do {
        alreadyExists = false;
        System.out.println("enter player" + loop + "s name");
        name = scanner.next();
        if (players.keySet().contains(name)) {
            System.out.println("name in use - enter new name");
            alreadyExists = true;
        } else {
            players.put(name, new Player());
        }
    } while (alreadyExists);
}
Sign up to request clarification or add additional context in comments.

Comments

0

I suppose you need a limited number of valid players.

while (players.size() < 4) {
        name = scanner.next();
        if(players.keySet().contains(name)) {
            System.out.println("name in use - enter new name");
        } else {
            players.put(name, new Player());
        }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.