[英]Why do I get null after I initialized a string?
I don't understand why Sp1.location returns NULL.我不明白为什么 Sp1.location 返回 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) {
}
}
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.因为您没有设置
location
,所以您将输入分配给pokemon
而不是iniLocation
并且当您调用函数来获取位置时,您会返回iniLocation
的值,该值尚未分配任何值,因此为空。 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.如果您在构造函数中初始化
scanner
对象,这是一个很好的做法。
class AnyClass{
Scanner scan;
public AnyClass(){
scan= new Scanner(System.in);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.