0

我最近花了几个月的时间在 C# 上给 Java,只是赶上了一些我不确定如何格式化的东西。

我整理了一个小例子来解释我的问题。

我正在尝试将“Creature”类型的对象添加到“Player”类型的对象中

目前是这样的:

                                                        //Null items are objects
Player newPlayer = new Player("This", "Is", "Here", 1 , 1, 1, null, null, null);        

Creature c = null;                                  //Null items are objects
c = new Creature("Name", "Species",  100, 5.5, 10.5, 1, 100, null, null, null);

newPlayer.addCreature(c);

但是我遇到的问题是java.lang.NullPointException.

播放器类可以在这里看到:

public Player(String Username, String Password, String Email, int Tokens, int Level, int Experience, Vector<Creature> Creature, Vector<Food> Food, Vector<Item> Item) {
    m_username = Username;
    m_password = Password;
    m_email = Email;
    m_tokens = Tokens;
    m_level = Level;
    m_experience = Experience;
    m_creature = Creature;
    m_food = Food;
    m_item = Item;

}   

public void addCreature(Creature c)
{
    m_creature.add(c);      
}

还有那个生物:

public Creature(String Name, String Species, int Health, double Damage, double Regen, int Level, int Exp, Vector<Effect> ActiveEffect, Vector<Attack> Attack, Vector<Specialisation> Specialisation )
{
    m_name = Name;
    m_species = Species;
    m_health = Health;
    m_damageMultiplier = Damage;
    m_regenRate = Regen;
    m_level = Level;
    m_experience = Exp;
    m_activeEffect = ActiveEffect;      
    m_attack = Attack;
    m_specialisation = Specialisation;      

}

如何使用它创建实例?

4

2 回答 2

1

那是因为对您存储的向量的引用是null. 您正在null为构造函数传递 s 。

当您通过时,new vector<Creature>()您实际上是在传递对新构造的向量的引用。它还没有包含任何生物对象。早些时候它失败了,因为您试图add(..)在设置为 null 的引用上调用函数。

试试这个:

Player newPlayer = new Player("This", "Is", "Here", 1 , 1, 1, new Vector<Creature>(), new Vector<Food>(), new Vector<Item>());
                                                              ^ new empty vector      ^ new empty vector  ^ new empty vector
于 2012-12-09T13:38:25.387 回答
0

不看addCreature实现就不能说。仔细查看异常的 Stackstrace,它会显示异常发生的确切行号。

于 2012-12-09T13:31:49.097 回答