Reputation: 33
I don't understand why Sp1.location returns NULL. If I run the program it seams I can initialize location successfully. I have code a attribute as an integer in a similar way, but that gave me no problems.
public class Database {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Add a new spawnpoint.\n");
System.out.println("State the name of this spawnpoint: ");
Spawnpoints Sp1 = new Spawnpoints(getSpawnName());
System.out.println("Done");
System.out.println("Location: " + Sp1.getLocation()); //return as null
}
public static String spawnName;
public static String getSpawnName() {
spawnName = userInput.next();
return spawnName;
}
public void setSpawnName(String spawnName) {
this.spawnName = spawnName;
}
}
// Import libraries
import java.util.*;
This is my other class
public class Spawnpoints extends Database {
// Define scanner, so you can accept user input
static Scanner userInput = new Scanner(System.in);
// Define attributes of Spawnpoints
private String location;
private String iniLocation;
// Creator, method for creating a instance of Spawnpoints. Will be the actual spawnpoints
// I include a iniLocation so no user input is asked when calling on getLocation.
public Spawnpoints(String spawnName) {
getIniLocation();
}
// Setters & Getters getLocation
private String getIniLocation() {
System.out.println("State the location of this spawnpoint:\n");
pokemon = userInput.next ();
return iniLocation;
}
public void setIniLocation(String iniLocation) {
this.iniLocation = iniLocation;
}
public String getLocation() {
location = iniLocation;
return location;
}
public void setLocation(String location) {
this.location = location;
}
public static void main (String[] args) {
}
}
Upvotes: 1
Views: 79
Reputation: 37404
Because you are not setting the location
, you are assigning input to pokemon
instead of iniLocation
and when you call function to get location you get back the value of iniLocation
which has not been assigned any value so hence null. Read comments in code
private String getIniLocation() {
System.out.println("State the location of this spawnpoint:\n");
pokemon = userInput.next (); // remove this
iniLocation = userInput.next (); // with this
return iniLocation;
}
and it's a good practice if you initialize your scanner
object in constructor.
class AnyClass{
Scanner scan;
public AnyClass(){
scan= new Scanner(System.in);
}
}
Upvotes: 1