简体   繁体   English

通过构造函数在 ArrayList 中添加对象

[英]Add objects in an ArrayList through constructor

I am a beginner, and I am building a classical NimGame.我是初学者,我正在构建一个经典的 NimGame。 Before, I used to save the project using an array.之前,我曾经使用数组来保存项目。 Now, I modify it to apply the ArrayList to this time.现在,我修改它以将ArrayList应用到这次。 It seems no problem, though, the functions I've made are not working without any errors.不过,这似乎没有问题,我所做的功能无法正常工作,没有任何错误。 I couldn't figure out why.我不知道为什么。

For now, I tried to add the NimPlayer type into the new playerList , which is the ArrayList.现在,我尝试将NimPlayer类型添加到新的playerList中,即 ArrayList。 I put the ArrayList in the NimModel , and use the constructor from the NimPlayer to create new players.我将 ArrayList 放在NimModel中,并使用NimPlayer中的构造函数来创建新播放器。 The Nimsys is the main panel to give commands and receive user inputs. Nimsys是提供命令和接收用户输入的主面板。 That's why I separate them into three classes.这就是为什么我把它们分成三类。

The command is like this $addplayer userName,familyName,givenName .该命令就像这样$addplayer userName,familyName,givenName And the scanner should process the string and go through the constructor to be a new object.并且扫描器应该通过构造函数将字符串和 go 处理为新的 object。

Any help is highly appreciated, and thank you for your kindness and patience.非常感谢您的任何帮助,并感谢您的善意和耐心。

Here is my related code Nimsys :这是我的相关代码Nimsys

public class Nimsys {

private NimModel nimModel;

public static void main(String[] args) {
    Nimsys nimsys = new Nimsys();
    nimsys.processCommands();
}

private void processCommands() {
    this.nimModel = new NimModel();
    Scanner in = new Scanner(System.in);

    System.out.println("Welcome to Nim\n");
    while (true) {
        System.out.print('$');
        String commandin = in.nextLine().trim();

        if (commandin.equalsIgnoreCase("addplayer")) {
            addplayer(in);
        }
        if (commandin.equalsIgnoreCase("removeplayer")) {
            removeplayer(in);
        }

}

private String[] splitName(String inName) {
    String[] splittedLine = inName.split(",");
    String[] name = null;
    if (splittedLine.length == 3) {
        String userName = splittedLine[0].trim();
        String familyName = splittedLine[1].trim();
        String givenName = splittedLine[2].trim();
        name = new String[3];
        name[0] = userName;
        name[1] = familyName;
        name[2] = givenName;
    }
    return name;
}
private void addplayer(Scanner in) {
    String inName = in.nextLine().trim();
    String[] name = splitName(inName);

    if (name != null && name.length == 3) {
        ArrayList<NimPlayer> playerList = nimModel.getPlayerList();
        for (NimPlayer player: playerList) {
            if (player.getUserName().contains(name[0])) {
                System.out.println("The player already exists.");
                return;
            } else {
                nimModel.createPlayer(name[0], name[1], name[2]);
                System.out.println("The player has been created.");
            }
        }        
    } 
private void removeplayer(Scanner in) {
    String removeUserName = in.nextLine().trim();
    NimPlayer player = nimModel.removePlayer(removeUserName);
    if (player == null) {
        System.out.println("The player does not exist");
    } else {
        System.out.println("Player " + player.getUserName() + 
                " removed successfully!");
    }
}

And the NimModel :NimModel

public class NimModel {

private NimPlayer nimplayer;

private ArrayList<NimPlayer> playerList = new ArrayList<>();

public void createPlayer(String userName, String familyName, String givenName) {
    NimPlayer player = new NimPlayer(userName, familyName, givenName);
    playerList.add(player);     

}

public ArrayList<NimPlayer> getPlayerList() {
    return playerList;
}
public NimPlayer removePlayer(String userName) {
    for (NimPlayer player: playerList) {
        String nameCheck = nimplayer.getUserName();
        String playerName = player.getUserName();
        if (playerName.equals(nameCheck)) {
            playerList.remove(player);
            break;
        } 
    }
    return null;

Lastly, NimPlayer class最后, NimPlayer class

public class NimPlayer {


private final String userName;
private String familyName;
private String givenName;

private int gamesPlayed;
private int gamesWon;
private int winRatio;



public NimPlayer(String userName, String familyName, String givenName) {

    this.userName = userName;
    this.familyName = familyName;
    this.givenName = givenName;
    this.gamesPlayed = 0;
    this.gamesWon = 0;
}
//getters and setters
}

in a nutschell:简而言之:

private void addplayer(Scanner in) {
String inName = in.nextLine().trim();
String[] name = splitName(inName);
if (name != null && name.length == 3) {
    ArrayList<NimPlayer> playerList = nimModel.getPlayerList();
    for (NimPlayer player: playerList) {
        if (player.getUserName().contains(name[0])) {
            System.out.println("The player already exists.");
            return;
        }
    }
    nimModel.createPlayer(name[0], name[1], name[2]);
    System.out.println("The player has been created.");         
}

Furthermore, your addPlayer() given in Nimsys is defined in your While(true) but I think it's more a typing error.此外,您在 Nimsys 中给出的 addPlayer() 是在您的 While(true) 中定义的,但我认为这更像是一个打字错误。 Personally I would also give a constructor to your model:我个人也会给你的 model 一个构造函数:

import java.util.ArrayList;

public class NimModel {

private NimPlayer nimplayer;

private ArrayList<NimPlayer> playerList;
public NimModel()
{
   this.playerList =  new ArrayList<NimPlayer>();
}
public void createPlayer(String userName, String familyName, String givenName) {
    NimPlayer player = new NimPlayer(userName, familyName, givenName);
    playerList.add(player);

}

public ArrayList<NimPlayer> getPlayerList() {
    return playerList;
}

public NimPlayer removePlayer(String userName) {
    for (NimPlayer player : playerList) {
        String nameCheck = nimplayer.getUserName();
        String playerName = player.getUserName();
        if (playerName.equals(nameCheck)) {
            playerList.remove(player);
            break;
        }
    }
    return null;
}
}

When you use scanner.nextLine() you are asking for a new input to the user.当您使用scanner.nextLine() 时,您是在向用户请求新的输入。 So if you want the format: $addplayer user,firstName,lastName you have to fetch it into a string and use this string:因此,如果您想要格式: $addplayer user,firstName,lastName您必须将其提取到字符串中并使用此字符串:

while (true) {
        System.out.print('$');
        String commandin = in.nextLine().trim();

        if (commandin.split(" ")[0].equalsIgnoreCase("addplayer")) {
            addplayer(commandin);
        }
    }
}

private void addplayer(String commandin) {
    String inName = commandin.split(" ")[1];
    String[] name = splitName(inName);
      ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM