0

我正在编写一个简单的命令行游戏。我有很多功能和所有,这里只会发布必要的。

问题:程序编译但是当levelup()被调用并选择了一个数字时,我得到了这个:

        You have 5 skill points to spend.
        What would you like to upgrade?
        [1:]    STR                     [2:]    DEF
1
Exception in thread "main" java.lang.NullPointerException
        at Game.levelup(cmdquest.java:300)
        at Game.start(cmdquest.java:336)
        at Menu.show_menu(cmdquest.java:195)
        at cmdquest.main(cmdquest.java:263)

这是我的代码:

class Player{
    String name;
    int hp;
    int str;
    int def;
    String  eff;

    Player(String n) {
    name = n;
    hp = 100;
    str = 1;
    def = 1;
    eff = "none";
    }
}


class Game{

    static Player p;

    static void levelup(){
        while (points > 0){
            System.out.println("\t[1:]\tSTR\t\t\t[2:]\tDEF");
            int lvlup = kb.nextInt();

            switch (lvlup){
                case 1: p.str++;
                    break;
                case 2: p.def++;
                    break;
            }

            points--;
        }

    //variables
    static Scanner kb = new Scanner(System.in);
    static int points = 5;

    }

static void start(){

        System.out.print("\t\t\t\tAnd so our adventure starts.....");

        System.out.print("\tWhat's your name: ");
        String nome = kb.next();
        Player p = new Player(nome);

        System.out.println("\tHello " + p.name);
        System.out.println("\tYou have 5 skill points to spend.\n\tWhat would you like to upgrade?");
        levelup();

    }



class cmdquest{

public static void main(String args[]) throws Exception{

    Scanner kb = new Scanner(System.in);

    //Importing foes.txt to create objects of foes
    java.io.File file = new java.io.File("foes.txt");
    Scanner imp = new Scanner(file);  

    for(int i =0; i<3; i++){
        foes[i]=foe.leDados(imp);
    }
    //____________________________________________

    Game.start();

}
}

谁能在这里指出我正确的方向?我究竟做错了什么?我觉得这是“玩家”类和在“游戏”类中创建的对象的类问题。

4

1 回答 1

6

你得到一个NullPointerException因为pis null。你在这里做了什么:

Player p = new Player(nome);

是声明一个局部变量p。静态类变量p保持不变,所以它仍然是null.

这称为阴影(JLS,第 6.4.1 节)

某些声明可能在其范围的一部分被另一个同名声明所遮蔽,在这种情况下,不能使用简单名称来引用声明的实体。

...

名为 n 的类型的声明 d 会遮蔽任何其他名为 n 的类型的声明,这些类型在 d 出现在整个 d 范围内的点上。

Remove Player,因此对静态类变量的引用p就是您想要的:

p = new Player(nome);
于 2013-09-23T17:03:04.693 回答