使用非空对象过滤数组后如何再次添加对象 [英] How to add object again after filtering array with non-null object

查看:118
本文介绍了使用非空对象过滤数组后如何再次添加对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在仅使用数组构建经典的Nim游戏,发现测试后存在错误。如果成功创建了播放器,我将为该阵列分配一个新对象。但是,在删除数组中的播放器时,我会使用非空对象过滤数组,因为我还有其他功能,例如 editplayer displayplayer 迭代整个数组而没有 NullPointerException

I am building a classical Nim game using only the array, and I found there is a bug after testing. If I successfully create a player, I'll assign a new object to the array. However, when removing the player in the array, I filter the array with non-null objects because I have other functions such as editplayer, displayplayer to iterate the entire array without NullPointerException.

而且有可能发生这种情况: addplayer removeplayer addplayer 。这意味着当我尝试向已经充满非空对象的数组分配新对象时,我总是得到 IndexOutOfBound

And there is a chance that this happens: addplayerremoveplayeraddplayer. It means I'll always get IndexOutOfBound when I try to assign a new object to the array already full of the non-null objects.

我已经搜索了所有可能的信息,但是对此没有讨论。有什么方法可以同时避免 NullPointerException IndexOutOfBound

I've searched for all the information I could, but there is no such discussion about this. Is there any way to avoid both NullPointerException and IndexOutOfBound at the same time?

这里是相关代码 Nimsys

public class Nimsys {

public static void addPlayer(String [] name) {
    if (name != null && name.length == 3) {
        for (int i = 0; i < NimPlayer.getCounter(); i++) {
            String userCheck = NimPlayer.getPlayer()[i].getUserName();
            if (userCheck.contains(name[0])) {
                System.out.println("The player already exists.\n");// Test if player has been created
                return;
            }
        }
        NimPlayer.createPlayer(name[0], name[1], name[2]);
        System.out.println("The player has been created.");
        return;
    } 
    System.out.println("Not Valid! Please enter again!");   
}

public static void searchAndRemovePlayer(String user) {
    NimPlayer [] playerList = NimPlayer.getPlayer();
    for (int i = 0; i < playerList.length; i++) {
        String userName =playerList[i].getUserName().trim();
        if (userName.equals(user)) {
            playerList[i] = null;
            System.out.println("Remove successfully!");
            NimPlayer.setPlayerList(playerList);
            return;
        }
    }
    System.out.println("The player does not exist.\n");

}
}

这里是<$ c的一部分$ c> NimPlayer 类:

public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;

private static int counter;
private static final int SIZE = 10;
private static NimPlayer[] playerList = new NimPlayer[SIZE]; // set an array here


//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 static void createPlayer(String userName, String familyName, String givenName) {
    if (counter < SIZE) {
        playerList[counter++] = new NimPlayer(userName, familyName, givenName);
    } else {
        System.out.println("Cannot add more players.");
    }
}
public static int getCounter() {
    return counter;
}
public static NimPlayer [] getPlayer() {      
    return playerList;
}
public static void setPlayerList(NimPlayer [] newplayerList) {
    playerList = Arrays.stream(newplayerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
    counter = playerList.length;  //update the counter
}
    //setters and getters of the other variables
}


推荐答案


  1. 我建议您仔细阅读 NullPointerException ArrayIndexOutOfBoundsException 。处理这些异常时,处理它们并不重要。但是,最重要的是要防止它们发生,即您应该了解根本原因并进行处理。众所周知,预防胜于治疗。

  2. 您应该始终尝试从类中隐藏尽可能多的信息,例如您已经有一个 public静态void createPlayer ,那么,为什么要创建一个 public 构造函数?为什么要为计数器创建一个公用吸气剂,该吸气剂只能在类<$ c中内部使用$ c> NimPlayer ?

  3. 您应该删除 playerList ,而不是从外部设置其 public 设置程序,并创建 public static void removePlayer 类似于 public static void createPlayer

  1. Instead of explaining about these exceptions, I recommend you go through the documentation of NullPointerException and ArrayIndexOutOfBoundsException. It is not a big deal to handle these exceptions when they occur. However, the most important thing is to prevent them i.e. you should understand what is the root cause and work on them. We all know, "Prevention is better than cure.".
  2. You should always try to hide as much information from the class as is possible e.g. you already have a public static void createPlayer then, why have you created a public constructor? Why have you created a public getter for counter which is meant to be used only internally in the class, NimPlayer?
  3. Instead of exposing the playerList to be set from outside, you should remove its public setter and create public static void removePlayer similar to public static void createPlayer.

边注上(因为它不会影响执行程序),标识符的名称应不言自明,例如您的 getPlayer 方法应命名为 getPlayerList ,因为它会返回 playerList ,而不是一个玩家。

On a side note (because it won't affect the execution of the program), the name of an identifier should be self-explanatory e.g. your getPlayer method should be named as getPlayerList as it is returning the playerList, not a single player.

下面给出的代码包含以下注释:

Given below is the code incorporating these comments:

import java.util.Arrays;
import java.util.Objects;

class NimPlayer {
    private String userName;
    private String familyName;
    private String givenName;
    private int score;
    private int gamePlayed;

    private static int counter;
    private static final int SIZE = 10;
    private static NimPlayer[] playerList = new NimPlayer[SIZE];

    private NimPlayer(String userName, String surName, String givenName) {
        this.userName = userName;
        this.familyName = surName;
        this.givenName = givenName;
    }

    public static void createPlayer(String userName, String familyName, String givenName) {
        if (counter < SIZE) {
            playerList[counter++] = new NimPlayer(userName, familyName, givenName);
        } else {
            System.out.println("Cannot add more players.");
        }
    }

    public static void removePlayer(NimPlayer player) {
        int i;
        for (i = 0; i < playerList.length; i++) {
            if (playerList[i] != null && playerList[i].getUserName().equals(player.getUserName())) {
                break;
            }
        }
        for (int j = i; j < playerList.length - 1; j++) {
            playerList[j] = playerList[j + 1];
        }
        counter--;
    }

    public static NimPlayer[] getPlayerList() {
        return Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
    }

    public String getUserName() {
        return userName;
    }

    public String getFamilyName() {
        return familyName;
    }

    public String getGivenName() {
        return givenName;
    }

    @Override
    public String toString() {
        return userName + " " + familyName + " " + givenName;
    }
}

class NimSys {

    public static void addPlayer(String[] name) {
        if (name != null && name.length == 3) {
            NimPlayer[] playerList = NimPlayer.getPlayerList();
            for (int i = 0; i < playerList.length; i++) {
                String userCheck = playerList[i].getUserName();
                if (userCheck.contains(name[0])) {
                    System.out.println("The player, " + name[0] + " already exists.\n");
                    return;
                }
            }
            NimPlayer.createPlayer(name[0], name[1], name[2]);
            System.out.println("The player, " + name[0] + "  has been created.");
            return;
        }
        System.out.println("Not Valid! Please enter again!");
    }

    public static void searchAndRemovePlayer(String user) {
        NimPlayer[] playerList = NimPlayer.getPlayerList();
        for (int i = 0; i < playerList.length; i++) {
            String userName = playerList[i].getUserName().trim();
            if (userName.equals(user)) {
                NimPlayer.removePlayer(playerList[i]);
                System.out.println("The player, " + user + " removed successfully!");
                return;
            }
        }
        System.out.println("The player, " + user + "  does not exist.\n");
    }

    public static void displayPlayerList() {
        NimPlayer[] playerList = NimPlayer.getPlayerList();
        StringBuilder sb = new StringBuilder();
        for (NimPlayer player : playerList) {
            sb.append(player.getUserName()).append(" ").append(player.getFamilyName()).append(" ")
                    .append(player.getGivenName()).append(System.lineSeparator());
        }
        System.out.println(sb);
    }
}

public class Main {
    public static void main(String[] args) {

        NimSys.addPlayer(new String[] { "Harry", "Potter", "Harry" });
        NimSys.displayPlayerList();

        NimSys.searchAndRemovePlayer("Harry");
        NimSys.displayPlayerList();

        NimSys.addPlayer(new String[] { "Manny", "Richard", "Canty" });
        NimSys.displayPlayerList();

        NimSys.addPlayer(new String[] { "Arvind", "Kumar", "Avinash" });
        NimSys.displayPlayerList();

        NimSys.searchAndRemovePlayer("Manny");
        NimSys.displayPlayerList();

        NimSys.addPlayer(new String[] { "Ken", "Ken", "Thompson" });
        NimSys.displayPlayerList();

        NimSys.searchAndRemovePlayer("Ken");
        NimSys.displayPlayerList();

        NimSys.addPlayer(new String[] { "Ken", "Ken", "Thompson" });
        NimSys.displayPlayerList();

        NimSys.searchAndRemovePlayer("Ken");
        NimSys.displayPlayerList();

        NimSys.addPlayer(new String[] { "Ken", "Ken", "Thompson" });
        NimSys.displayPlayerList();
    }
}

输出:

The player, Harry  has been created.
Harry Potter Harry

The player, Harry removed successfully!

The player, Manny  has been created.
Manny Richard Canty

The player, Arvind  has been created.
Manny Richard Canty
Arvind Kumar Avinash

The player, Manny removed successfully!
Arvind Kumar Avinash

The player, Ken  has been created.
Arvind Kumar Avinash
Ken Ken Thompson

The player, Ken removed successfully!
Arvind Kumar Avinash

The player, Ken  has been created.
Arvind Kumar Avinash
Ken Ken Thompson

The player, Ken removed successfully!
Arvind Kumar Avinash

The player, Ken  has been created.
Arvind Kumar Avinash
Ken Ken Thompson

这篇关于使用非空对象过滤数组后如何再次添加对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆