我正在编写一个简单的命令行游戏。 我已经有很多功能了,这里只发布必要的功能。
问题:程序可以编译,但是当调用 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();
}
}
有人能指出我正确的方向吗? 我究竟做错了什么?我感觉这是“Player”类和“Game”类中创建的对象的类问题。
最佳答案
您会得到一个 NullPointerException
,因为 p
是 null
。您在这里所做的事情:
Player p = new Player(nome);
声明一个本地变量p
。静态类变量 p
未受影响,因此它仍为 null
。
这称为shadowing (JLS, Section 6.4.1) :
Some declarations may be shadowed in part of their scope by another declaration of the same name, in which case a simple name cannot be used to refer to the declared entity.
...
A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occurs throughout the scope of d.
删除Player
,因此对静态类变量p
的引用就是您想要的:
p = new Player(nome);
关于java - NullPointerException 但编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18964869/