I am a java beginner and I am designing a Nim game for many players to join. I've done some research but I don't know if my implementation is correct. The aim is to check the duplicate object in an array. I've already checked some articles, and I'll reference them in the last part of this article.
For the NimPlayer class. I've created some things.
- I've defined the NimPlayer object type.
- Using the type, I can initialize the player in the limited space.
I initialize an array for saving player's data by following the steps here: Storing object into an array - Java
public class NimPlayer { String userName; String familyName; String givenName; NimPlayer [] playerList = new NimPlayer[10]; //set an array here int id; //define NimPlayer data type public NimPlayer(String userName,String surName, String givenName) { this.userName = userName; this.familyName = surName; this.givenName = givenName; } //create new data using NimPlayer data type public void createPlayer(String userName, String familyName, String givenName) { playerList[id++] = new NimPlayer(userName, familyName, givenName); }
In the main method, I have created some features for players to use:
- addplayer - let the user can add players in the game to compete.
To add the player, the Syntax like this:
$addplayer userName,familyName,givenName
to validate the input, I split the input and store them in the new object.
public static String[] splitName(String inputName) { String [] splittedLine = inputName.split(","); String userName = splittedLine[0].trim(); String familyName = splittedLine[1].trim(); String givenName = splittedLine[2].trim(); String [] name = new String[3]; name[0] = userName; name[1] = familyName; name[2] = givenName; return name; } public static void main(String[] args) { Scanner in = new Scanner(System.in); //create new object to save data NimPlayer playerData = new NimPlayer(null, null, null); System.out.print('$'); String commandInput = in.next(); while (true) { if (commandInput.equals("addplayer")) { String inputName = in.nextLine(); String[] name = splitName(inputName); String userName = name[0]; String familyName = name [1]; String givenName = name[2]; playerData.createPlayer(userName, familyName, givenName); for (int i = 0; i < playerData.playerList.length; i++) { NimPlayer player = playerData.playerList[i]; System.out.println(player.getUserName()); } }
So far, I have two questions here.
Every time I enter a set of data, it seems my "playerData" provokes the NullPointerException when looping through the object, but since my name input is multiple, I have to create a new object in the main method for saving input.
For checking if there is the duplicate "userName" in the set of the "inputName", I loop through the objects in an array. How can I access the "userName" in this situation?
for checking duplicate, I've checked: