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()
is called and a number is chosen, I get this:
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)
Here is my code:
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();
}
}
Can anyone point me in the right direction here? What am I doing wrong? I sense it's a class problem with the class "Player" and the object being created in the "Game" class.
You get a
NullPointerException
becausep
isnull
. What you've done here:is declare a local variable
p
. The static class variablep
is untouched, so it remainsnull
.This is called shadowing (JLS, Section 6.4.1):
...
Remove
Player
, so the reference to the static class variablep
is what you want: