0

我在收到此错误时遇到问题:

线程“主”java.lang.NullPointerException 中的异常

在 com.noxia.Main.startCombat(Main.java:101)

在 com.noxia.Area1.createArea1Enemy(Area1.java:43)

在 com.noxia.Main.main(Main.java:30)

我知道我需要初始化变量,因为它们为空,但我似乎无法弄清楚我需要把什么放在哪里。我已将代码最小化以仅显示相关部分,因为遗漏了许多其他变量和方法,但这似乎与问题有关。任何帮助将不胜感激 =)

public class Main {
    Player p;
    Enemy e;
    Area1 a1;        

    public static void main(String[] args) {
        Main main = new Main();
        main.a1 = new Area1();            
        main.p = new Player(100);
        //the line directly below this is line 30 where the error occurs
        main.a1.createArea1Enemy(10);
    }

    public void startCombat()
    {
        //the line directly below this is line 101 where the error occurs       
        while (p.getCurrentLife() > 0 & a1.e.getLife() > 0)
        {
            p.playerAttack();
            if (p.getCurrentLife() > 0 & a1.e.getLife() > 0)
            {
                e.enemyAttack();
            }
        }   
    }


public class Player extends Main {
    private int currentLife;

    public int getCurrentLife()
    {
        return currentLife;
    }
    public void setCurrentLife(int cl)
    {
        currentLife = cl;
    }

    public Player(int cl)
    {
        currentLife = cl;
    }


public class Enemy extends Main {
    private int life;

    public int getLife()
    {
        return life;
    }
    public void setLife(int lf)
    {
        life = lf;
    }

    public Enemy (inf lf)
    {
        life = lf;
    }


public class Area1 extends Main {

    public void createArea1Enemy(int enemyCounter)
    {
        while (enemyCounter > 0)
        {
            String[] enemyList = {"Enemy1", "Enemy2"} //code for Enemy2 left out below
            int enemyListLength = enemyList.length; 
            int randomEnemy = (int) (Math.random() * enemyListLength);

            if (enemyList[randomEnemy].equals("Enemy1"))
            {
                Enemy enemy1 = new Enemy("Enemy1", 100);
                //the line directly below this is line 43 where the error occurs
                startCombat();
            }
        enemyCounter--;
        }
    }
}
4

3 回答 3

3

简单的答案是你必须e在调用之前设置一个敌人startCombat

但更好的方法是删除e,并将敌人对象传递给startCombat使用方法参数。该e字段在概念上是错误的。Main要理解错误,请尝试根据对象的状态对它的含义做出连贯的解释。


显然这是初学者代码......你写的东西有很多不好的地方:

  • 类的字段应该用于对象状态,而不是用于将参数值传递给方法。
  • 你应该避免编写访问类内部的代码......就像你的 main 方法一样。
  • 最佳实践是为外部类创建字段private,并定义 getter 和/或 setter 方法(根据需要)以访问/修改它们。
  • 您需要学习如何编写带参数的构造函数。
  • 您需要正确设计代码。一切扩展都Main意味着不会有关于对象“意味着”什么的理性模型。还有一个问题,Enemy和的每个实例Area1都有自己的 、 和 字段的副本pe以及a1一大堆不合适的方法。
于 2012-06-24T01:22:36.413 回答
2

主要问题是您从不初始化Enemy e;. 您创建了一个敌人,但从未将其分配给this.e.

更改此行:

Enemy enemy1 = new Enemy("Enemy1", 100);

对此:

this.e = new Enemy("Enemy1", 100);

您的代码还有许多其他问题。

于 2012-06-24T01:17:54.197 回答
1

了解如何正确编写构造函数。这段代码是错误的。

我完全看不出为什么 a PlayArea1Enemy应该扩展 Main。

于 2012-06-24T01:18:10.533 回答