Home > Back-end >  How to ensure two players or more inputted player names in an arraylist are not the same (java)
How to ensure two players or more inputted player names in an arraylist are not the same (java)

Time:11-09

Hello in my monopoly game i need to make sure no inputted player names are the same to avoid confusion using an arraylist in java any way how to do it so only one player can have one name

public class Player {
    private ArrayList<Property> properties = new ArrayList<Property>();
    private final String name;
    private int position;
    private int money = 0;
    public boolean inJail = false;
    public int outOfJailCards = 0;
    public int turnsInJail = 0;
    public Player(String name){
        this.name = name;
        position = 0;
    }
    public String getName() { 
        return name;
         }

// in monopoly.java
static ArrayList<Player> createPlayers(int numPlayers){
        ArrayList<Player> players = new ArrayList<>();

        for(int i = 1; i <= numPlayers; i  ){
            System.out.print("Player "   i   " name: ");
            
            players.add(new Player(Input.read()));
        }

        return players;
    }
}

import java.util.List;
import java.util.Scanner;

public class Input {
    public static String read(){
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }

enter image description here

CodePudding user response:

Instead of directly adding the player to the array list, check with .contains() first. If not, ask for re-input. You will not be able to do this directly with a for loop, you will need to restructure your code.

PS: This sounds very much like homework in a programming course.

CodePudding user response:

you can save the input from the user into a variable and check if the name already exists in the list:

String input = Input.read();
if(!list.stream().findAny(s -> s.getName().equals(input)).isPresent()({
   players.add(new Player(input));
}

Stream API were used to check if name already exists in the list, but you could also use the .contains method, but first you need to override the equals method in your Player class.

  • Related