NullPointerException but compiling?

前端 未结 1 1824
醉梦人生
醉梦人生 2021-01-27 13:30

I\'m writing a simple command line game. I\'ve got many functions and all, and will only post the essential here.

Problem: The program compiles but when levelup()<

相关标签:
1条回答
  • 2021-01-27 14:00

    You get a NullPointerException because p is null. What you've done here:

    Player p = new Player(nome);
    

    is declare a local variable p. The static class variable p is untouched, so it remains null.

    This is called 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.

    Remove Player, so the reference to the static class variable p is what you want:

    p = new Player(nome);
    
    0 讨论(0)
提交回复
热议问题